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