Extract SIGPIPE ignoring code to a common place.
[chromium-blink-merge.git] / chrome / common / extensions / extension.h
blob56e1af451e51dd30b4c3a59d42034b0156836e5c
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_COMMON_EXTENSIONS_EXTENSION_H_
6 #define CHROME_COMMON_EXTENSIONS_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/file_path.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/hash_tables.h"
19 #include "base/memory/linked_ptr.h"
20 #include "base/memory/ref_counted.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/synchronization/lock.h"
23 #include "chrome/common/extensions/command.h"
24 #include "chrome/common/extensions/extension_constants.h"
25 #include "chrome/common/extensions/extension_icon_set.h"
26 #include "chrome/common/extensions/permissions/api_permission.h"
27 #include "chrome/common/extensions/permissions/api_permission_set.h"
28 #include "chrome/common/extensions/permissions/permission_message.h"
29 #include "chrome/common/extensions/url_pattern_set.h"
30 #include "chrome/common/extensions/user_script.h"
31 #include "extensions/common/url_pattern.h"
32 #include "googleurl/src/gurl.h"
33 #include "ui/base/accelerators/accelerator.h"
34 #include "ui/gfx/size.h"
36 class ExtensionAction;
37 class ExtensionResource;
38 class FileBrowserHandler;
39 class SkBitmap;
40 class Version;
42 namespace base {
43 class DictionaryValue;
44 class ListValue;
47 namespace gfx {
48 class ImageSkia;
51 namespace webkit_glue {
52 struct WebIntentServiceData;
55 FORWARD_DECLARE_TEST(TabStripModelTest, Apps);
57 namespace extensions {
59 class Manifest;
60 class PermissionSet;
62 typedef std::set<std::string> OAuth2Scopes;
64 // Represents a Chrome extension.
65 class Extension : public base::RefCountedThreadSafe<Extension> {
66 public:
67 struct InstallWarning;
69 typedef std::map<const std::string, GURL> URLOverrideMap;
70 typedef std::vector<std::string> ScriptingWhitelist;
71 typedef std::vector<linked_ptr<FileBrowserHandler> > FileBrowserHandlerList;
72 typedef std::vector<InstallWarning> InstallWarningVector;
74 // What an extension was loaded from.
75 // NOTE: These values are stored as integers in the preferences and used
76 // in histograms so don't remove or reorder existing items. Just append
77 // to the end.
78 enum Location {
79 INVALID,
80 INTERNAL, // A crx file from the internal Extensions directory.
81 EXTERNAL_PREF, // A crx file from an external directory (via prefs).
82 EXTERNAL_REGISTRY, // A crx file from an external directory (via eg the
83 // registry on Windows).
84 LOAD, // --load-extension.
85 COMPONENT, // An integral component of Chrome itself, which
86 // happens to be implemented as an extension. We don't
87 // show these in the management UI.
88 EXTERNAL_PREF_DOWNLOAD, // A crx file from an external directory (via
89 // prefs), installed from an update URL.
90 EXTERNAL_POLICY_DOWNLOAD, // A crx file from an external directory (via
91 // admin policies), installed from an update URL.
93 NUM_LOCATIONS
96 enum State {
97 DISABLED = 0,
98 ENABLED,
99 // An external extension that the user uninstalled. We should not reinstall
100 // such extensions on startup.
101 EXTERNAL_EXTENSION_UNINSTALLED,
102 NUM_STATES
105 // Used to record the reason an extension was disabled.
106 enum DeprecatedDisableReason {
107 DEPRECATED_DISABLE_UNKNOWN,
108 DEPRECATED_DISABLE_USER_ACTION,
109 DEPRECATED_DISABLE_PERMISSIONS_INCREASE,
110 DEPRECATED_DISABLE_RELOAD,
111 DEPRECATED_DISABLE_LAST, // Not used.
114 enum DisableReason {
115 DISABLE_NONE = 0,
116 DISABLE_USER_ACTION = 1 << 0,
117 DISABLE_PERMISSIONS_INCREASE = 1 << 1,
118 DISABLE_RELOAD = 1 << 2,
119 DISABLE_UNSUPPORTED_REQUIREMENT = 1 << 3,
120 DISABLE_SIDELOAD_WIPEOUT = 1 << 4,
123 enum InstallType {
124 INSTALL_ERROR,
125 DOWNGRADE,
126 REINSTALL,
127 UPGRADE,
128 NEW_INSTALL
131 // Do not change the order of entries or remove entries in this list
132 // as this is used in UMA_HISTOGRAM_ENUMERATIONs about extensions.
133 enum Type {
134 TYPE_UNKNOWN = 0,
135 TYPE_EXTENSION,
136 TYPE_THEME,
137 TYPE_USER_SCRIPT,
138 TYPE_HOSTED_APP,
139 // This is marked legacy because platform apps are preferred. For
140 // backwards compatibility, we can't remove support for packaged apps
141 TYPE_LEGACY_PACKAGED_APP,
142 TYPE_PLATFORM_APP
145 enum SyncType {
146 SYNC_TYPE_NONE = 0,
147 SYNC_TYPE_EXTENSION,
148 SYNC_TYPE_APP
151 // Declared requirements for the extension.
152 struct Requirements {
153 Requirements();
154 ~Requirements();
156 bool webgl;
157 bool css3d;
158 bool npapi;
161 // An NPAPI plugin included in the extension.
162 struct PluginInfo {
163 FilePath path; // Path to the plugin.
164 bool is_public; // False if only this extension can load this plugin.
167 // An NaCl module included in the extension.
168 struct NaClModuleInfo {
169 GURL url;
170 std::string mime_type;
173 enum InputComponentType {
174 INPUT_COMPONENT_TYPE_NONE = -1,
175 INPUT_COMPONENT_TYPE_IME,
176 INPUT_COMPONENT_TYPE_COUNT
179 struct InputComponentInfo {
180 // Define out of line constructor/destructor to please Clang.
181 InputComponentInfo();
182 ~InputComponentInfo();
184 std::string name;
185 InputComponentType type;
186 std::string id;
187 std::string description;
188 std::string language;
189 std::set<std::string> layouts;
190 std::string shortcut_keycode;
191 bool shortcut_alt;
192 bool shortcut_ctrl;
193 bool shortcut_shift;
196 struct TtsVoice {
197 // Define out of line constructor/destructor to please Clang.
198 TtsVoice();
199 ~TtsVoice();
201 std::string voice_name;
202 std::string lang;
203 std::string gender;
204 std::set<std::string> event_types;
207 // OAuth2 info included in the extension.
208 struct OAuth2Info {
209 OAuth2Info();
210 ~OAuth2Info();
212 OAuth2Scopes GetScopesAsSet();
214 std::string client_id;
215 std::vector<std::string> scopes;
218 struct ActionInfo {
219 explicit ActionInfo();
220 ~ActionInfo();
222 // The types of extension actions.
223 enum Type {
224 TYPE_BROWSER,
225 TYPE_PAGE,
226 TYPE_SCRIPT_BADGE,
229 // Empty implies the key wasn't present.
230 ExtensionIconSet default_icon;
231 std::string default_title;
232 GURL default_popup_url;
233 // action id -- only used with legacy page actions API.
234 std::string id;
237 struct InstallWarning {
238 enum Format {
239 // IMPORTANT: Do not build HTML strings from user or developer-supplied
240 // input.
241 FORMAT_TEXT,
242 FORMAT_HTML,
244 InstallWarning(Format format, const std::string& message)
245 : format(format), message(message) {
247 bool operator==(const InstallWarning& other) const;
248 Format format;
249 std::string message;
252 enum InitFromValueFlags {
253 NO_FLAGS = 0,
255 // Usually, the id of an extension is generated by the "key" property of
256 // its manifest, but if |REQUIRE_KEY| is not set, a temporary ID will be
257 // generated based on the path.
258 REQUIRE_KEY = 1 << 0,
260 // Requires the extension to have an up-to-date manifest version.
261 // Typically, we'll support multiple manifest versions during a version
262 // transition. This flag signals that we want to require the most modern
263 // manifest version that Chrome understands.
264 REQUIRE_MODERN_MANIFEST_VERSION = 1 << 1,
266 // |ALLOW_FILE_ACCESS| indicates that the user is allowing this extension
267 // to have file access. If it's not present, then permissions and content
268 // scripts that match file:/// URLs will be filtered out.
269 ALLOW_FILE_ACCESS = 1 << 2,
271 // |FROM_WEBSTORE| indicates that the extension was installed from the
272 // Chrome Web Store.
273 FROM_WEBSTORE = 1 << 3,
275 // |FROM_BOOKMARK| indicates the extension was created using a mock App
276 // created from a bookmark.
277 FROM_BOOKMARK = 1 << 4,
279 // |FOLLOW_SYMLINKS_ANYWHERE| means that resources can be symlinks to
280 // anywhere in the filesystem, rather than being restricted to the
281 // extension directory.
282 FOLLOW_SYMLINKS_ANYWHERE = 1 << 5,
284 // |ERROR_ON_PRIVATE_KEY| means that private keys inside an
285 // extension should be errors rather than warnings.
286 ERROR_ON_PRIVATE_KEY = 1 << 6,
288 // |WAS_INSTALLED_BY_DEFAULT| installed by default when the profile was
289 // created.
290 WAS_INSTALLED_BY_DEFAULT = 1 << 7,
293 static scoped_refptr<Extension> Create(const FilePath& path,
294 Location location,
295 const base::DictionaryValue& value,
296 int flags,
297 std::string* error);
299 // In a few special circumstances, we want to create an Extension and give it
300 // an explicit id. Most consumers should just use the other Create() method.
301 static scoped_refptr<Extension> Create(const FilePath& path,
302 Location location,
303 const base::DictionaryValue& value,
304 int flags,
305 const std::string& explicit_id,
306 std::string* error);
308 // Given two install sources, return the one which should take priority
309 // over the other. If an extension is installed from two sources A and B,
310 // its install source should be set to GetHigherPriorityLocation(A, B).
311 static Location GetHigherPriorityLocation(Location loc1, Location loc2);
313 // Max size (both dimensions) for browser and page actions.
314 static const int kPageActionIconMaxSize;
315 static const int kBrowserActionIconMaxSize;
317 // Valid schemes for web extent URLPatterns.
318 static const int kValidWebExtentSchemes;
320 // Valid schemes for host permission URLPatterns.
321 static const int kValidHostPermissionSchemes;
323 // The name of the manifest inside an extension.
324 static const FilePath::CharType kManifestFilename[];
326 // The name of locale folder inside an extension.
327 static const FilePath::CharType kLocaleFolder[];
329 // The name of the messages file inside an extension.
330 static const FilePath::CharType kMessagesFilename[];
332 #if defined(OS_WIN)
333 static const char kExtensionRegistryPath[];
334 #endif
336 // The number of bytes in a legal id.
337 static const size_t kIdSize;
339 // The mimetype used for extensions.
340 static const char kMimeType[];
342 // Checks to see if the extension has a valid ID.
343 static bool IdIsValid(const std::string& id);
345 // Generate an ID for an extension in the given path.
346 // Used while developing extensions, before they have a key.
347 static std::string GenerateIdForPath(const FilePath& file_name);
349 // Returns true if the specified file is an extension.
350 static bool IsExtension(const FilePath& file_name);
352 // Whether the |location| is external or not.
353 static inline bool IsExternalLocation(Location location) {
354 return location == Extension::EXTERNAL_PREF ||
355 location == Extension::EXTERNAL_REGISTRY ||
356 location == Extension::EXTERNAL_PREF_DOWNLOAD ||
357 location == Extension::EXTERNAL_POLICY_DOWNLOAD;
360 // Whether extensions with |location| are auto-updatable or not.
361 static inline bool IsAutoUpdateableLocation(Location location) {
362 // Only internal and external extensions can be autoupdated.
363 return location == Extension::INTERNAL ||
364 IsExternalLocation(location);
367 // Policy-required extensions are silently auto-installed and updated, and
368 // cannot be disabled or modified by the user in any way. The same applies
369 // to internal components.
370 // This method is not generally called directly; instead, it is accessed
371 // through the ManagementPolicy held by the ExtensionSystem.
372 static inline bool IsRequired(Location location) {
373 return location == Extension::EXTERNAL_POLICY_DOWNLOAD ||
374 location == Extension::COMPONENT;
377 // Unpacked extensions start off with file access since they are a developer
378 // feature.
379 static inline bool ShouldAlwaysAllowFileAccess(Location location) {
380 return location == Extension::LOAD;
383 // Fills the |info| dictionary with basic information about the extension.
384 // |enabled| is injected for easier testing.
385 void GetBasicInfo(bool enabled, base::DictionaryValue* info) const;
387 // See Type definition above.
388 Type GetType() const;
390 // Returns an absolute url to a resource inside of an extension. The
391 // |extension_url| argument should be the url() from an Extension object. The
392 // |relative_path| can be untrusted user input. The returned URL will either
393 // be invalid() or a child of |extension_url|.
394 // NOTE: Static so that it can be used from multiple threads.
395 static GURL GetResourceURL(const GURL& extension_url,
396 const std::string& relative_path);
397 GURL GetResourceURL(const std::string& relative_path) const {
398 return GetResourceURL(url(), relative_path);
401 // Returns true if the resource matches a pattern in the pattern_set.
402 bool ResourceMatches(const URLPatternSet& pattern_set,
403 const std::string& resource) const;
405 // Returns true if the specified resource is web accessible.
406 bool IsResourceWebAccessible(const std::string& relative_path) const;
408 // Returns true if the specified page is sandboxed (served in a unique
409 // origin).
410 bool IsSandboxedPage(const std::string& relative_path) const;
412 // Returns the Content Security Policy that the specified resource should be
413 // served with.
414 std::string GetResourceContentSecurityPolicy(const std::string& relative_path)
415 const;
417 // Returns true when 'web_accessible_resources' are defined for the extension.
418 bool HasWebAccessibleResources() const;
420 // Returns an extension resource object. |relative_path| should be UTF8
421 // encoded.
422 ExtensionResource GetResource(const std::string& relative_path) const;
424 // As above, but with |relative_path| following the file system's encoding.
425 ExtensionResource GetResource(const FilePath& relative_path) const;
427 // |input| is expected to be the text of an rsa public or private key. It
428 // tolerates the presence or absence of bracking header/footer like this:
429 // -----(BEGIN|END) [RSA PUBLIC/PRIVATE] KEY-----
430 // and may contain newlines.
431 static bool ParsePEMKeyBytes(const std::string& input, std::string* output);
433 // Does a simple base64 encoding of |input| into |output|.
434 static bool ProducePEM(const std::string& input, std::string* output);
436 // Generates an extension ID from arbitrary input. The same input string will
437 // always generate the same output ID.
438 static bool GenerateId(const std::string& input,
439 std::string* output) WARN_UNUSED_RESULT;
441 // Expects base64 encoded |input| and formats into |output| including
442 // the appropriate header & footer.
443 static bool FormatPEMForFileOutput(const std::string& input,
444 std::string* output,
445 bool is_public);
447 // Given an extension, icon size, and match type, read a valid icon if present
448 // and decode it into result. In the browser process, this will DCHECK if not
449 // called on the file thread. To easily load extension images on the UI
450 // thread, see ImageLoadingTracker.
451 static void DecodeIcon(const Extension* extension,
452 int icon_size,
453 ExtensionIconSet::MatchType match_type,
454 scoped_ptr<SkBitmap>* result);
456 // Given an extension and icon size, read it if present and decode it into
457 // result. In the browser process, this will DCHECK if not called on the
458 // file thread. To easily load extension images on the UI thread, see
459 // ImageLoadingTracker.
460 static void DecodeIcon(const Extension* extension,
461 int icon_size,
462 scoped_ptr<SkBitmap>* result);
464 // Given an icon_path and icon size, read it if present and decode it into
465 // result. In the browser process, this will DCHECK if not called on the
466 // file thread. To easily load extension images on the UI thread, see
467 // ImageLoadingTracker.
468 static void DecodeIconFromPath(const FilePath& icon_path,
469 int icon_size,
470 scoped_ptr<SkBitmap>* result);
472 // Returns the default extension/app icon (for extensions or apps that don't
473 // have one).
474 static const gfx::ImageSkia& GetDefaultIcon(bool is_app);
476 // Returns the base extension url for a given |extension_id|.
477 static GURL GetBaseURLFromExtensionId(const std::string& extension_id);
479 // Adds an extension to the scripting whitelist. Used for testing only.
480 static void SetScriptingWhitelist(const ScriptingWhitelist& whitelist);
481 static const ScriptingWhitelist* GetScriptingWhitelist();
483 // Parses the host and api permissions from the specified permission |key|
484 // from |manifest_|.
485 bool ParsePermissions(const char* key,
486 string16* error,
487 APIPermissionSet* api_permissions,
488 URLPatternSet* host_permissions);
490 bool HasAPIPermission(APIPermission::ID permission) const;
491 bool HasAPIPermission(const std::string& function_name) const;
492 bool HasAPIPermissionForTab(int tab_id, APIPermission::ID permission) const;
494 bool CheckAPIPermissionWithParam(APIPermission::ID permission,
495 const APIPermission::CheckParam* param) const;
497 const URLPatternSet& GetEffectiveHostPermissions() const;
499 // Returns true if the extension can silently increase its permission level.
500 // Users must approve permissions for unpacked and packed extensions in the
501 // following situations:
502 // - when installing or upgrading packed extensions
503 // - when installing unpacked extensions that have NPAPI plugins
504 // - when either type of extension requests optional permissions
505 bool CanSilentlyIncreasePermissions() const;
507 // Whether the extension has access to the given URL.
508 bool HasHostPermission(const GURL& url) const;
510 // Whether the extension has effective access to all hosts. This is true if
511 // there is a content script that matches all hosts, if there is a host
512 // permission grants access to all hosts (like <all_urls>) or an api
513 // permission that effectively grants access to all hosts (e.g. proxy,
514 // network, etc.)
515 bool HasEffectiveAccessToAllHosts() const;
517 // Whether the extension effectively has all permissions (for example, by
518 // having an NPAPI plugin).
519 bool HasFullPermissions() const;
521 // Returns the full list of permission messages that this extension
522 // should display at install time.
523 PermissionMessages GetPermissionMessages() const;
525 // Returns the full list of permission messages that this extension
526 // should display at install time. The messages are returned as strings
527 // for convenience.
528 std::vector<string16> GetPermissionMessageStrings() const;
530 // Returns true if the extension does not require permission warnings
531 // to be displayed at install time.
532 bool ShouldSkipPermissionWarnings() const;
534 // Sets the active |permissions|.
535 void SetActivePermissions(const PermissionSet* permissions) const;
537 // Gets the extension's active permission set.
538 scoped_refptr<const PermissionSet> GetActivePermissions() const;
540 // Whether context menu should be shown for page and browser actions.
541 bool ShowConfigureContextMenus() const;
543 // Returns the Homepage URL for this extension. If homepage_url was not
544 // specified in the manifest, this returns the Google Gallery URL. For
545 // third-party extensions, this returns a blank GURL.
546 GURL GetHomepageURL() const;
548 // Returns a list of paths (relative to the extension dir) for images that
549 // the browser might load (like themes and page action icons).
550 std::set<FilePath> GetBrowserImages() const;
552 // Get an extension icon as a resource or URL.
553 ExtensionResource GetIconResource(
554 int size, ExtensionIconSet::MatchType match_type) const;
555 GURL GetIconURL(int size, ExtensionIconSet::MatchType match_type) const;
557 // Gets the fully resolved absolute launch URL.
558 GURL GetFullLaunchURL() const;
560 // Image cache related methods. These are only valid on the UI thread and
561 // not maintained by this class. See ImageLoadingTracker for usage. The
562 // |original_size| parameter should be the size of the image at |source|
563 // before any scaling may have been done to produce the pixels in |image|.
564 void SetCachedImage(const ExtensionResource& source,
565 const SkBitmap& image,
566 const gfx::Size& original_size) const;
567 bool HasCachedImage(const ExtensionResource& source,
568 const gfx::Size& max_size) const;
569 SkBitmap GetCachedImage(const ExtensionResource& source,
570 const gfx::Size& max_size) const;
572 // Returns true if this extension can execute script on a page. If a
573 // UserScript object is passed, permission to run that specific script is
574 // checked (using its matches list). Otherwise, permission to execute script
575 // programmatically is checked (using the extension's host permission).
577 // This method is also aware of certain special pages that extensions are
578 // usually not allowed to run script on.
579 bool CanExecuteScriptOnPage(const GURL& document_url,
580 const GURL& top_document_url,
581 int tab_id,
582 const UserScript* script,
583 std::string* error) const;
585 // Returns true if this extension is a COMPONENT extension, or if it is
586 // on the whitelist of extensions that can script all pages.
587 bool CanExecuteScriptEverywhere() const;
589 // Returns true if this extension is allowed to obtain the contents of a
590 // page as an image. Since a page may contain sensitive information, this
591 // is restricted to the extension's host permissions as well as the
592 // extension page itself.
593 bool CanCaptureVisiblePage(const GURL& page_url,
594 int tab_id,
595 std::string* error) const;
597 // Returns true if this extension updates itself using the extension
598 // gallery.
599 bool UpdatesFromGallery() const;
601 // Returns true if this extension or app includes areas within |origin|.
602 bool OverlapsWithOrigin(const GURL& origin) const;
604 // Returns the sync bucket to use for this extension.
605 SyncType GetSyncType() const;
607 // Returns true if the extension should be synced.
608 bool IsSyncable() const;
610 // Returns true if the extension requires a valid ordinal for sorting, e.g.,
611 // for displaying in a launcher or new tab page.
612 bool RequiresSortOrdinal() const;
614 // Returns true if the extension should be displayed in the app launcher.
615 bool ShouldDisplayInAppLauncher() const;
617 // Returns true if the extension should be displayed in the browser NTP.
618 bool ShouldDisplayInNewTabPage() const;
620 // Returns true if the extension should be displayed in the extension
621 // settings page (i.e. chrome://extensions).
622 bool ShouldDisplayInExtensionSettings() const;
624 // Returns true if the extension has a content script declared at |url|.
625 bool HasContentScriptAtURL(const GURL& url) const;
627 // Gets the tab-specific host permissions of |tab_id|, or NULL if there
628 // aren't any.
629 scoped_refptr<const PermissionSet> GetTabSpecificPermissions(int tab_id)
630 const;
632 // Updates the tab-specific permissions of |tab_id| to include those from
633 // |permissions|.
634 void UpdateTabSpecificPermissions(
635 int tab_id,
636 scoped_refptr<const PermissionSet> permissions) const;
638 // Clears the tab-specific permissions of |tab_id|.
639 void ClearTabSpecificPermissions(int tab_id) const;
641 // Accessors:
643 const Requirements& requirements() const { return requirements_; }
644 const FilePath& path() const { return path_; }
645 const GURL& url() const { return extension_url_; }
646 Location location() const;
647 const std::string& id() const;
648 const Version* version() const { return version_.get(); }
649 const std::string VersionString() const;
650 const std::string& name() const { return name_; }
651 const std::string& non_localized_name() const { return non_localized_name_; }
652 // Base64-encoded version of the key used to sign this extension.
653 // In pseudocode, returns
654 // base::Base64Encode(RSAPrivateKey(pem_file).ExportPublicKey()).
655 const std::string& public_key() const { return public_key_; }
656 const std::string& description() const { return description_; }
657 int manifest_version() const { return manifest_version_; }
658 bool converted_from_user_script() const {
659 return converted_from_user_script_;
661 const UserScriptList& content_scripts() const { return content_scripts_; }
662 const ActionInfo* script_badge_info() const {
663 return script_badge_info_.get();
665 const ActionInfo* page_action_info() const { return page_action_info_.get(); }
666 const ActionInfo* browser_action_info() const {
667 return browser_action_info_.get();
669 bool is_verbose_install_message() const {
670 return !omnibox_keyword().empty() ||
671 browser_action_info() ||
672 (page_action_info() &&
673 (page_action_command() ||
674 !page_action_info()->default_icon.empty()));
676 const FileBrowserHandlerList* file_browser_handlers() const {
677 return file_browser_handlers_.get();
679 const std::vector<PluginInfo>& plugins() const { return plugins_; }
680 const std::vector<NaClModuleInfo>& nacl_modules() const {
681 return nacl_modules_;
683 const std::vector<InputComponentInfo>& input_components() const {
684 return input_components_;
686 // The browser action command that the extension wants to use, which is not
687 // necessarily the one it can use, as it might be inactive (see also
688 // GetBrowserActionCommand in CommandService).
689 const extensions::Command* browser_action_command() const {
690 return browser_action_command_.get();
692 // The page action command that the extension wants to use, which is not
693 // necessarily the one it can use, as it might be inactive (see also
694 // GetPageActionCommand in CommandService).
695 const extensions::Command* page_action_command() const {
696 return page_action_command_.get();
698 // The script badge command that the extension wants to use, which is not
699 // necessarily the one it can use, as it might be inactive (see also
700 // GetScriptBadgeCommand in CommandService).
701 const extensions::Command* script_badge_command() const {
702 return script_badge_command_.get();
704 // The map (of command names to commands) that the extension wants to use,
705 // which is not necessarily the one it can use, as they might be inactive
706 // (see also GetNamedCommands in CommandService).
707 const extensions::CommandMap& named_commands() const {
708 return named_commands_;
710 bool has_background_page() const {
711 return background_url_.is_valid() || !background_scripts_.empty();
713 bool allow_background_js_access() const {
714 return allow_background_js_access_;
716 const std::vector<std::string>& background_scripts() const {
717 return background_scripts_;
719 bool has_persistent_background_page() const {
720 return has_background_page() && background_page_is_persistent_;
722 bool has_lazy_background_page() const {
723 return has_background_page() && !background_page_is_persistent_;
725 const GURL& options_url() const { return options_url_; }
726 const GURL& devtools_url() const { return devtools_url_; }
727 const GURL& details_url() const { return details_url_;}
728 const PermissionSet* optional_permission_set() const {
729 return optional_permission_set_.get();
731 const PermissionSet* required_permission_set() const {
732 return required_permission_set_.get();
734 // Appends |new_warnings| to install_warnings().
735 void AddInstallWarnings(const InstallWarningVector& new_warnings);
736 const InstallWarningVector& install_warnings() const {
737 return install_warnings_;
739 const GURL& update_url() const { return update_url_; }
740 const ExtensionIconSet& icons() const { return icons_; }
741 const extensions::Manifest* manifest() const {
742 return manifest_.get();
744 const std::string default_locale() const { return default_locale_; }
745 const URLOverrideMap& GetChromeURLOverrides() const {
746 return chrome_url_overrides_;
748 const std::string omnibox_keyword() const { return omnibox_keyword_; }
749 bool incognito_split_mode() const { return incognito_split_mode_; }
750 bool offline_enabled() const { return offline_enabled_; }
751 const std::vector<TtsVoice>& tts_voices() const { return tts_voices_; }
752 const OAuth2Info& oauth2_info() const { return oauth2_info_; }
753 const std::vector<webkit_glue::WebIntentServiceData>&
754 intents_services() const {
755 return intents_services_;
758 bool wants_file_access() const { return wants_file_access_; }
759 int creation_flags() const { return creation_flags_; }
760 bool from_webstore() const { return (creation_flags_ & FROM_WEBSTORE) != 0; }
761 bool from_bookmark() const { return (creation_flags_ & FROM_BOOKMARK) != 0; }
762 bool was_installed_by_default() const {
763 return (creation_flags_ & WAS_INSTALLED_BY_DEFAULT) != 0;
766 // App-related.
767 bool is_app() const {
768 return is_legacy_packaged_app() || is_hosted_app() || is_platform_app();
770 bool is_platform_app() const;
771 bool is_hosted_app() const;
772 bool is_legacy_packaged_app() const;
773 bool is_storage_isolated() const { return is_storage_isolated_; }
774 const URLPatternSet& web_extent() const { return extent_; }
775 const std::string& launch_local_path() const { return launch_local_path_; }
776 const std::string& launch_web_url() const { return launch_web_url_; }
777 extension_misc::LaunchContainer launch_container() const {
778 return launch_container_;
780 int launch_width() const { return launch_width_; }
781 int launch_height() const { return launch_height_; }
783 // Theme-related.
784 bool is_theme() const;
785 base::DictionaryValue* GetThemeImages() const { return theme_images_.get(); }
786 base::DictionaryValue* GetThemeColors() const {return theme_colors_.get(); }
787 base::DictionaryValue* GetThemeTints() const { return theme_tints_.get(); }
788 base::DictionaryValue* GetThemeDisplayProperties() const {
789 return theme_display_properties_.get();
792 GURL GetBackgroundURL() const;
794 private:
795 friend class base::RefCountedThreadSafe<Extension>;
797 // We keep a cache of images loaded from extension resources based on their
798 // path and a string representation of a size that may have been used to
799 // scale it (or the empty string if the image is at its original size).
800 typedef std::pair<FilePath, std::string> ImageCacheKey;
801 typedef std::map<ImageCacheKey, SkBitmap> ImageCache;
803 class RuntimeData {
804 public:
805 RuntimeData();
806 explicit RuntimeData(const PermissionSet* active);
807 ~RuntimeData();
809 void SetActivePermissions(const PermissionSet* active);
810 scoped_refptr<const PermissionSet> GetActivePermissions() const;
812 scoped_refptr<const PermissionSet> GetTabSpecificPermissions(int tab_id)
813 const;
814 void UpdateTabSpecificPermissions(
815 int tab_id,
816 scoped_refptr<const PermissionSet> permissions);
817 void ClearTabSpecificPermissions(int tab_id);
819 private:
820 friend class base::RefCountedThreadSafe<RuntimeData>;
822 scoped_refptr<const PermissionSet> active_permissions_;
824 typedef std::map<int, scoped_refptr<const PermissionSet> >
825 TabPermissionsMap;
826 TabPermissionsMap tab_specific_permissions_;
829 // Chooses the extension ID for an extension based on a variety of criteria.
830 // The chosen ID will be set in |manifest|.
831 static bool InitExtensionID(extensions::Manifest* manifest,
832 const FilePath& path,
833 const std::string& explicit_id,
834 int creation_flags,
835 string16* error);
837 // Normalize the path for use by the extension. On Windows, this will make
838 // sure the drive letter is uppercase.
839 static FilePath MaybeNormalizePath(const FilePath& path);
841 // Returns true if this extension id is from a trusted provider.
842 static bool IsTrustedId(const std::string& id);
844 Extension(const FilePath& path, scoped_ptr<extensions::Manifest> manifest);
845 ~Extension();
847 // Initialize the extension from a parsed manifest.
848 // TODO(aa): Rename to just Init()? There's no Value here anymore.
849 // TODO(aa): It is really weird the way this class essentially contains a copy
850 // of the underlying DictionaryValue in its members. We should decide to
851 // either wrap the DictionaryValue and go with that only, or we should parse
852 // into strong types and discard the value. But doing both is bad.
853 bool InitFromValue(int flags, string16* error);
855 // The following are helpers for InitFromValue to load various features of the
856 // extension from the manifest.
858 bool LoadAppIsolation(const APIPermissionSet& api_permissions,
859 string16* error);
861 bool LoadRequiredFeatures(string16* error);
862 bool LoadName(string16* error);
863 bool LoadVersion(string16* error);
865 bool LoadAppFeatures(string16* error);
866 bool LoadExtent(const char* key,
867 URLPatternSet* extent,
868 const char* list_error,
869 const char* value_error,
870 string16* error);
871 bool LoadLaunchContainer(string16* error);
872 bool LoadLaunchURL(string16* error);
874 bool LoadSharedFeatures(const APIPermissionSet& api_permissions,
875 string16* error);
876 bool LoadDescription(string16* error);
877 bool LoadManifestVersion(string16* error);
878 bool LoadHomepageURL(string16* error);
879 bool LoadUpdateURL(string16* error);
880 bool LoadIcons(string16* error);
881 bool LoadCommands(string16* error);
882 bool LoadPlugins(string16* error);
883 bool LoadNaClModules(string16* error);
884 bool LoadWebAccessibleResources(string16* error);
885 bool LoadSandboxedPages(string16* error);
886 // Must be called after LoadPlugins().
887 bool LoadRequirements(string16* error);
888 bool LoadDefaultLocale(string16* error);
889 bool LoadOfflineEnabled(string16* error);
890 bool LoadOptionsPage(string16* error);
891 bool LoadBackgroundScripts(string16* error);
892 bool LoadBackgroundScripts(const std::string& key, string16* error);
893 bool LoadBackgroundPage(const APIPermissionSet& api_permissions,
894 string16* error);
895 bool LoadBackgroundPage(const std::string& key,
896 const APIPermissionSet& api_permissions,
897 string16* error);
898 bool LoadBackgroundPersistent(
899 const APIPermissionSet& api_permissions,
900 string16* error);
901 bool LoadBackgroundAllowJSAccess(
902 const APIPermissionSet& api_permissions,
903 string16* error);
904 // Parses a single action in the manifest.
905 bool LoadWebIntentAction(const std::string& action_name,
906 const base::DictionaryValue& intent_service,
907 string16* error);
908 bool LoadWebIntentServices(string16* error);
909 bool LoadFileHandler(const std::string& handler_id,
910 const base::DictionaryValue& handler_info,
911 string16* error);
912 bool LoadFileHandlers(string16* error);
913 bool LoadExtensionFeatures(const APIPermissionSet& api_permissions,
914 string16* error);
915 bool LoadDevToolsPage(string16* error);
916 bool LoadInputComponents(const APIPermissionSet& api_permissions,
917 string16* error);
918 bool LoadContentScripts(string16* error);
919 bool LoadPageAction(string16* error);
920 bool LoadBrowserAction(string16* error);
921 bool LoadScriptBadge(string16* error);
922 bool LoadFileBrowserHandlers(string16* error);
923 // Helper method to load a FileBrowserHandlerList from the manifest.
924 FileBrowserHandlerList* LoadFileBrowserHandlersHelper(
925 const base::ListValue* extension_actions, string16* error);
926 // Helper method to load an FileBrowserHandler from manifest.
927 FileBrowserHandler* LoadFileBrowserHandler(
928 const base::DictionaryValue* file_browser_handlers, string16* error);
929 bool LoadChromeURLOverrides(string16* error);
930 bool LoadOmnibox(string16* error);
931 bool LoadTextToSpeechVoices(string16* error);
932 bool LoadIncognitoMode(string16* error);
933 bool LoadContentSecurityPolicy(string16* error);
935 bool LoadThemeFeatures(string16* error);
936 bool LoadThemeImages(const base::DictionaryValue* theme_value,
937 string16* error);
938 bool LoadThemeColors(const base::DictionaryValue* theme_value,
939 string16* error);
940 bool LoadThemeTints(const base::DictionaryValue* theme_value,
941 string16* error);
942 bool LoadThemeDisplayProperties(const base::DictionaryValue* theme_value,
943 string16* error);
945 // Helper function for implementing HasCachedImage/GetCachedImage. A return
946 // value of NULL means there is no matching image cached (we allow caching an
947 // empty SkBitmap).
948 SkBitmap* GetCachedImageImpl(const ExtensionResource& source,
949 const gfx::Size& max_size) const;
951 // Helper method that loads a UserScript object from a
952 // dictionary in the content_script list of the manifest.
953 bool LoadUserScriptHelper(const base::DictionaryValue* content_script,
954 int definition_index,
955 string16* error,
956 UserScript* result);
958 // Helper method that loads either the include_globs or exclude_globs list
959 // from an entry in the content_script lists of the manifest.
960 bool LoadGlobsHelper(const base::DictionaryValue* content_script,
961 int content_script_index,
962 const char* globs_property_name,
963 string16* error,
964 void(UserScript::*add_method)(const std::string& glob),
965 UserScript* instance);
967 // Helper method to load an ExtensionAction from the page_action or
968 // browser_action entries in the manifest.
969 scoped_ptr<ActionInfo> LoadExtensionActionInfoHelper(
970 const base::DictionaryValue* manifest_section,
971 ActionInfo::Type action_type,
972 string16* error);
974 // Helper method that loads the OAuth2 info from the 'oauth2' manifest key.
975 bool LoadOAuth2Info(string16* error);
977 // Returns true if the extension has more than one "UI surface". For example,
978 // an extension that has a browser action and a page action.
979 bool HasMultipleUISurfaces() const;
981 // Updates the launch URL and extents for the extension using the given
982 // |override_url|.
983 void OverrideLaunchUrl(const GURL& override_url);
985 // Custom checks for the experimental permission that can't be expressed in
986 // _permission_features.json.
987 bool CanSpecifyExperimentalPermission() const;
989 // Checks whether the host |pattern| is allowed for this extension, given API
990 // permissions |permissions|.
991 bool CanSpecifyHostPermission(const URLPattern& pattern,
992 const APIPermissionSet& permissions) const;
994 bool CheckMinimumChromeVersion(string16* error) const;
996 // Check that platform app features are valid. Called after InitFromValue.
997 bool CheckPlatformAppFeatures(std::string* utf8_error) const;
999 // Check that features don't conflict. Called after InitFromValue.
1000 bool CheckConflictingFeatures(std::string* utf8_error) const;
1002 // Cached images for this extension. This should only be touched on the UI
1003 // thread.
1004 mutable ImageCache image_cache_;
1006 // The extension's human-readable name. Name is used for display purpose. It
1007 // might be wrapped with unicode bidi control characters so that it is
1008 // displayed correctly in RTL context.
1009 // NOTE: Name is UTF-8 and may contain non-ascii characters.
1010 std::string name_;
1012 // A non-localized version of the extension's name. This is useful for
1013 // debug output.
1014 std::string non_localized_name_;
1016 // The version of this extension's manifest. We increase the manifest
1017 // version when making breaking changes to the extension system.
1018 // Version 1 was the first manifest version (implied by a lack of a
1019 // manifest_version attribute in the extension's manifest). We initialize
1020 // this member variable to 0 to distinguish the "uninitialized" case from
1021 // the case when we know the manifest version actually is 1.
1022 int manifest_version_;
1024 // The requirements declared in the manifest.
1025 Requirements requirements_;
1027 // The absolute path to the directory the extension is stored in.
1028 FilePath path_;
1030 // Default locale for fall back. Can be empty if extension is not localized.
1031 std::string default_locale_;
1033 // If true, a separate process will be used for the extension in incognito
1034 // mode.
1035 bool incognito_split_mode_;
1037 // Whether the extension or app should be enabled when offline.
1038 bool offline_enabled_;
1040 // Defines the set of URLs in the extension's web content.
1041 URLPatternSet extent_;
1043 // The extension runtime data.
1044 mutable base::Lock runtime_data_lock_;
1045 mutable RuntimeData runtime_data_;
1047 // The set of permissions the extension can request at runtime.
1048 scoped_refptr<const PermissionSet> optional_permission_set_;
1050 // The extension's required / default set of permissions.
1051 scoped_refptr<const PermissionSet> required_permission_set_;
1053 // Any warnings that occurred when trying to create/parse the extension.
1054 InstallWarningVector install_warnings_;
1056 // The icons for the extension.
1057 ExtensionIconSet icons_;
1059 // The base extension url for the extension.
1060 GURL extension_url_;
1062 // The extension's version.
1063 scoped_ptr<Version> version_;
1065 // An optional longer description of the extension.
1066 std::string description_;
1068 // True if the extension was generated from a user script. (We show slightly
1069 // different UI if so).
1070 bool converted_from_user_script_;
1072 // Paths to the content scripts the extension contains.
1073 UserScriptList content_scripts_;
1075 // The extension's page action, if any.
1076 scoped_ptr<ActionInfo> page_action_info_;
1078 // The extension's browser action, if any.
1079 scoped_ptr<ActionInfo> browser_action_info_;
1081 // The extension's script badge. Never NULL.
1082 scoped_ptr<ActionInfo> script_badge_info_;
1084 // The extension's file browser actions, if any.
1085 scoped_ptr<FileBrowserHandlerList> file_browser_handlers_;
1087 // Optional list of NPAPI plugins and associated properties.
1088 std::vector<PluginInfo> plugins_;
1090 // Optional list of NaCl modules and associated properties.
1091 std::vector<NaClModuleInfo> nacl_modules_;
1093 // Optional list of input components and associated properties.
1094 std::vector<InputComponentInfo> input_components_;
1096 // Optional list of commands (keyboard shortcuts).
1097 scoped_ptr<extensions::Command> browser_action_command_;
1098 scoped_ptr<extensions::Command> page_action_command_;
1099 scoped_ptr<extensions::Command> script_badge_command_;
1100 extensions::CommandMap named_commands_;
1102 // Optional list of web accessible extension resources.
1103 URLPatternSet web_accessible_resources_;
1105 // Optional list of extension pages that are sandboxed (served from a unique
1106 // origin with a different Content Security Policy).
1107 URLPatternSet sandboxed_pages_;
1109 // Content Security Policy that should be used to enforce the sandbox used
1110 // by sandboxed pages (guaranteed to have the "sandbox" directive without the
1111 // "allow-same-origin" token).
1112 std::string sandboxed_pages_content_security_policy_;
1114 // Optional URL to a master page of which a single instance should be always
1115 // loaded in the background.
1116 GURL background_url_;
1118 // Optional list of scripts to use to generate a background page. If this is
1119 // present, background_url_ will be empty and generated by GetBackgroundURL().
1120 std::vector<std::string> background_scripts_;
1122 // True if the background page should stay loaded forever; false if it should
1123 // load on-demand (when it needs to handle an event). Defaults to true.
1124 bool background_page_is_persistent_;
1126 // True if the background page can be scripted by pages of the app or
1127 // extension, in which case all such pages must run in the same process.
1128 // False if such pages are not permitted to script the background page,
1129 // allowing them to run in different processes.
1130 bool allow_background_js_access_;
1132 // Optional URL to a page for setting options/preferences.
1133 GURL options_url_;
1135 // Optional URL to a devtools extension page.
1136 GURL devtools_url_;
1138 // URL to the webstore page of the extension.
1139 GURL details_url_;
1141 // The public key used to sign the contents of the crx package.
1142 std::string public_key_;
1144 // A map of resource id's to relative file paths.
1145 scoped_ptr<base::DictionaryValue> theme_images_;
1147 // A map of color names to colors.
1148 scoped_ptr<base::DictionaryValue> theme_colors_;
1150 // A map of color names to colors.
1151 scoped_ptr<base::DictionaryValue> theme_tints_;
1153 // A map of display properties.
1154 scoped_ptr<base::DictionaryValue> theme_display_properties_;
1156 // The homepage for this extension. Useful if it is not hosted by Google and
1157 // therefore does not have a Gallery URL.
1158 GURL homepage_url_;
1160 // URL for fetching an update manifest
1161 GURL update_url_;
1163 // The manifest from which this extension was created.
1164 scoped_ptr<Manifest> manifest_;
1166 // A map of chrome:// hostnames (newtab, downloads, etc.) to Extension URLs
1167 // which override the handling of those URLs. (see ExtensionOverrideUI).
1168 URLOverrideMap chrome_url_overrides_;
1170 // Whether this extension requests isolated storage.
1171 bool is_storage_isolated_;
1173 // The local path inside the extension to use with the launcher.
1174 std::string launch_local_path_;
1176 // A web url to use with the launcher. Note that this might be relative or
1177 // absolute. If relative, it is relative to web_origin.
1178 std::string launch_web_url_;
1180 // The window type that an app's manifest specifies to launch into.
1181 // This is not always the window type an app will open into, because
1182 // users can override the way each app launches. See
1183 // ExtensionPrefs::GetLaunchContainer(), which looks at a per-app pref
1184 // to decide what container an app will launch in.
1185 extension_misc::LaunchContainer launch_container_;
1187 // The default size of the container when launching. Only respected for
1188 // containers like panels and windows.
1189 int launch_width_;
1190 int launch_height_;
1192 // Should this app be shown in the app launcher.
1193 bool display_in_launcher_;
1195 // Should this app be shown in the browser New Tab Page.
1196 bool display_in_new_tab_page_;
1198 // The Omnibox keyword for this extension, or empty if there is none.
1199 std::string omnibox_keyword_;
1201 // List of text-to-speech voices that this extension provides, if any.
1202 std::vector<TtsVoice> tts_voices_;
1204 // The OAuth2 client id and scopes, if specified by the extension.
1205 OAuth2Info oauth2_info_;
1207 // List of intent services that this extension provides, if any.
1208 std::vector<webkit_glue::WebIntentServiceData> intents_services_;
1210 // Whether the extension has host permissions or user script patterns that
1211 // imply access to file:/// scheme URLs (the user may not have actually
1212 // granted it that access).
1213 bool wants_file_access_;
1215 // The flags that were passed to InitFromValue.
1216 int creation_flags_;
1218 // The Content-Security-Policy for this extension. Extensions can use
1219 // Content-Security-Policies to mitigate cross-site scripting and other
1220 // vulnerabilities.
1221 std::string content_security_policy_;
1223 FRIEND_TEST_ALL_PREFIXES(ExtensionTest, LoadPageActionHelper);
1224 FRIEND_TEST_ALL_PREFIXES(::TabStripModelTest, Apps);
1226 DISALLOW_COPY_AND_ASSIGN(Extension);
1229 typedef std::vector< scoped_refptr<const Extension> > ExtensionList;
1230 typedef std::set<std::string> ExtensionIdSet;
1231 typedef std::vector<std::string> ExtensionIdList;
1233 // Let gtest print InstallWarnings.
1234 void PrintTo(const Extension::InstallWarning&, ::std::ostream* os);
1236 // Handy struct to pass core extension info around.
1237 struct ExtensionInfo {
1238 ExtensionInfo(const base::DictionaryValue* manifest,
1239 const std::string& id,
1240 const FilePath& path,
1241 Extension::Location location);
1242 ~ExtensionInfo();
1244 scoped_ptr<base::DictionaryValue> extension_manifest;
1245 std::string extension_id;
1246 FilePath extension_path;
1247 Extension::Location extension_location;
1249 private:
1250 DISALLOW_COPY_AND_ASSIGN(ExtensionInfo);
1253 struct UnloadedExtensionInfo {
1254 extension_misc::UnloadedExtensionReason reason;
1256 // Was the extension already disabled?
1257 bool already_disabled;
1259 // The extension being unloaded - this should always be non-NULL.
1260 const Extension* extension;
1262 UnloadedExtensionInfo(
1263 const Extension* extension,
1264 extension_misc::UnloadedExtensionReason reason);
1267 // The details sent for EXTENSION_PERMISSIONS_UPDATED notifications.
1268 struct UpdatedExtensionPermissionsInfo {
1269 enum Reason {
1270 ADDED, // The permissions were added to the extension.
1271 REMOVED, // The permissions were removed from the extension.
1274 Reason reason;
1276 // The extension who's permissions have changed.
1277 const Extension* extension;
1279 // The permissions that have changed. For Reason::ADDED, this would contain
1280 // only the permissions that have added, and for Reason::REMOVED, this would
1281 // only contain the removed permissions.
1282 const PermissionSet* permissions;
1284 UpdatedExtensionPermissionsInfo(
1285 const Extension* extension,
1286 const PermissionSet* permissions,
1287 Reason reason);
1290 } // namespace extensions
1292 #endif // CHROME_COMMON_EXTENSIONS_EXTENSION_H_