1 // Copyright 2014 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 #include "extensions/browser/extension_prefs.h"
9 #include "base/command_line.h"
10 #include "base/prefs/pref_notifier.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_util.h"
14 #include "base/value_conversions.h"
15 #include "chrome/browser/extensions/api/content_settings/content_settings_store.h"
16 #include "chrome/browser/extensions/api/preference/preference_api.h"
17 #include "components/user_prefs/pref_registry_syncable.h"
18 #include "extensions/browser/admin_policy.h"
19 #include "extensions/browser/app_sorting.h"
20 #include "extensions/browser/event_router.h"
21 #include "extensions/browser/extension_pref_store.h"
22 #include "extensions/browser/extension_prefs_factory.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/feature_switch.h"
25 #include "extensions/common/manifest.h"
26 #include "extensions/common/permissions/permission_set.h"
27 #include "extensions/common/permissions/permissions_info.h"
28 #include "extensions/common/url_pattern.h"
29 #include "extensions/common/user_script.h"
30 #include "ui/base/l10n/l10n_util.h"
33 using base::DictionaryValue;
34 using base::ListValue;
36 namespace extensions {
40 // Additional preferences keys, which are not needed by external clients.
42 // True if this extension is running. Note this preference stops getting updated
43 // during Chrome shutdown (and won't be updated on a browser crash) and so can
44 // be used at startup to determine whether the extension was running when Chrome
45 // was last terminated.
46 const char kPrefRunning[] = "running";
48 // Whether this extension had windows when it was last running.
49 const char kIsActive[] = "is_active";
51 // Where an extension was installed from. (see Manifest::Location)
52 const char kPrefLocation[] = "location";
54 // Enabled, disabled, killed, etc. (see Extension::State)
55 const char kPrefState[] = "state";
57 // The path to the current version's manifest file.
58 const char kPrefPath[] = "path";
60 // The dictionary containing the extension's manifest.
61 const char kPrefManifest[] = "manifest";
63 // The version number.
64 const char kPrefVersion[] = "manifest.version";
66 // Indicates whether an extension is blacklisted.
67 const char kPrefBlacklist[] = "blacklist";
69 // If extension is greylisted.
70 const char kPrefBlacklistState[] = "blacklist_state";
72 // The count of how many times we prompted the user to acknowledge an
74 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
76 // Indicates whether the user has acknowledged various types of extensions.
77 const char kPrefExternalAcknowledged[] = "ack_external";
78 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
79 const char kPrefWipeoutAcknowledged[] = "ack_wiped";
81 // Indicates whether the external extension was installed during the first
82 // run of this profile.
83 const char kPrefExternalInstallFirstRun[] = "external_first_run";
85 // Indicates whether to show an install warning when the user enables.
86 const char kExtensionDidEscalatePermissions[] = "install_warning_on_enable";
88 // DO NOT USE, use kPrefDisableReasons instead.
89 // Indicates whether the extension was updated while it was disabled.
90 const char kDeprecatedPrefDisableReason[] = "disable_reason";
92 // A bitmask of all the reasons an extension is disabled.
93 const char kPrefDisableReasons[] = "disable_reasons";
95 // The key for a serialized Time value indicating the start of the day (from the
96 // server's perspective) an extension last included a "ping" parameter during
98 const char kLastPingDay[] = "lastpingday";
100 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
101 const char kLastActivePingDay[] = "last_active_pingday";
103 // A bit we use to keep track of whether we need to do an "active" ping.
104 const char kActiveBit[] = "active_bit";
106 // Path for settings specific to blacklist update.
107 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
109 // Path for the delayed install info dictionary preference. The actual string
110 // value is a legacy artifact for when delayed installs only pertained to
111 // updates that were waiting for idle.
112 const char kDelayedInstallInfo[] = "idle_install_info";
114 // Reason why the extension's install was delayed.
115 const char kDelayedInstallReason[] = "delay_install_reason";
117 // Path for the suggested page ordinal of a delayed extension install.
118 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
120 // A preference that, if true, will allow this extension to run in incognito
122 const char kPrefIncognitoEnabled[] = "incognito";
124 // A preference to control whether an extension is allowed to inject script in
125 // pages with file URLs.
126 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
127 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
128 // extension file access by renaming the pref. We should eventually clean up
129 // the old flag and possibly go back to that name.
130 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
132 // A preference specifying if the user dragged the app on the NTP.
133 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
135 // Preferences that hold which permissions the user has granted the extension.
136 // We explicitly keep track of these so that extensions can contain unknown
137 // permissions, for backwards compatibility reasons, and we can still prompt
138 // the user to accept them once recognized. We store the active permission
139 // permissions because they may differ from those defined in the manifest.
140 const char kPrefActivePermissions[] = "active_permissions";
141 const char kPrefGrantedPermissions[] = "granted_permissions";
143 // The preference names for PermissionSet values.
144 const char kPrefAPIs[] = "api";
145 const char kPrefManifestPermissions[] = "manifest_permissions";
146 const char kPrefExplicitHosts[] = "explicit_host";
147 const char kPrefScriptableHosts[] = "scriptable_host";
149 // The preference names for the old granted permissions scheme.
150 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
151 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
152 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
154 // A preference that indicates when an extension was installed.
155 const char kPrefInstallTime[] = "install_time";
157 // A preference which saves the creation flags for extensions.
158 const char kPrefCreationFlags[] = "creation_flags";
160 // A preference that indicates whether the extension was installed from the
162 const char kPrefFromWebStore[] = "from_webstore";
164 // A preference that indicates whether the extension was installed from a
165 // mock App created from a bookmark.
166 const char kPrefFromBookmark[] = "from_bookmark";
168 // A preference that indicates whether the extension was installed as
170 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
172 // Key for Geometry Cache preference.
173 const char kPrefGeometryCache[] = "geometry_cache";
175 // A preference that indicates when an extension is last launched.
176 const char kPrefLastLaunchTime[] = "last_launch_time";
178 // A list of installed ids and a signature.
179 const char kInstallSignature[] = "extensions.install_signature";
181 // Provider of write access to a dictionary storing extension prefs.
182 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
184 ScopedExtensionPrefUpdate(PrefService* service,
185 const std::string& extension_id) :
186 DictionaryPrefUpdate(service, pref_names::kExtensions),
187 extension_id_(extension_id) {}
189 virtual ~ScopedExtensionPrefUpdate() {
192 // DictionaryPrefUpdate overrides:
193 virtual base::DictionaryValue* Get() OVERRIDE {
194 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
195 base::DictionaryValue* extension = NULL;
196 if (!dict->GetDictionary(extension_id_, &extension)) {
197 // Extension pref does not exist, create it.
198 extension = new base::DictionaryValue();
199 dict->SetWithoutPathExpansion(extension_id_, extension);
205 const std::string extension_id_;
207 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
210 std::string JoinPrefs(const std::string& parent, const char* child) {
211 return parent + "." + child;
214 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
215 // Return false if the value is false or kPrefBlacklist does not exist.
216 // This is used to decide if an extension is blacklisted.
217 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
219 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
228 ExtensionPrefs::TimeProvider::TimeProvider() {
231 ExtensionPrefs::TimeProvider::~TimeProvider() {
234 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
235 return base::Time::Now();
241 template <typename T, base::Value::Type type_enum_value>
242 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
243 ExtensionPrefs* prefs,
244 const std::string& extension_id,
245 const std::string& key)
246 : update_(prefs->pref_service(), pref_names::kExtensions),
247 extension_id_(extension_id),
249 DCHECK(Extension::IdIsValid(extension_id_));
252 template <typename T, base::Value::Type type_enum_value>
253 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
256 template <typename T, base::Value::Type type_enum_value>
257 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
258 base::DictionaryValue* dict = update_.Get();
259 base::DictionaryValue* extension = NULL;
260 base::Value* key_value = NULL;
261 if (!dict->GetDictionary(extension_id_, &extension) ||
262 !extension->Get(key_, &key_value)) {
265 return key_value->GetType() == type_enum_value ?
266 static_cast<T*>(key_value) :
270 template <typename T, base::Value::Type type_enum_value>
271 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
272 base::DictionaryValue* dict = update_.Get();
273 base::DictionaryValue* extension = NULL;
274 base::Value* key_value = NULL;
275 T* value_as_t = NULL;
276 if (!dict->GetDictionary(extension_id_, &extension)) {
277 extension = new base::DictionaryValue;
278 dict->SetWithoutPathExpansion(extension_id_, extension);
280 if (!extension->Get(key_, &key_value)) {
282 extension->SetWithoutPathExpansion(key_, value_as_t);
284 CHECK(key_value->GetType() == type_enum_value);
285 value_as_t = static_cast<T*>(key_value);
290 // Explicit instantiations for Dictionary and List value types.
291 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
292 base::Value::TYPE_DICTIONARY>;
293 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
294 base::Value::TYPE_LIST>;
301 ExtensionPrefs* ExtensionPrefs::Create(
303 const base::FilePath& root_dir,
304 ExtensionPrefValueMap* extension_pref_value_map,
305 scoped_ptr<AppSorting> app_sorting,
306 bool extensions_disabled) {
307 return ExtensionPrefs::Create(prefs,
309 extension_pref_value_map,
312 make_scoped_ptr(new TimeProvider()));
316 ExtensionPrefs* ExtensionPrefs::Create(
317 PrefService* pref_service,
318 const base::FilePath& root_dir,
319 ExtensionPrefValueMap* extension_pref_value_map,
320 scoped_ptr<AppSorting> app_sorting,
321 bool extensions_disabled,
322 scoped_ptr<TimeProvider> time_provider) {
323 return new ExtensionPrefs(pref_service,
325 extension_pref_value_map,
327 time_provider.Pass(),
328 extensions_disabled);
331 ExtensionPrefs::~ExtensionPrefs() {
335 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
336 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
339 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
340 const base::FilePath& child) {
341 if (!parent.IsParent(child))
342 return child.value();
344 base::FilePath::StringType retval = child.value().substr(
345 parent.value().length());
346 if (base::FilePath::IsSeparator(retval[0]))
347 return retval.substr(1);
352 void ExtensionPrefs::MakePathsRelative() {
353 const base::DictionaryValue* dict =
354 prefs_->GetDictionary(pref_names::kExtensions);
355 if (!dict || dict->empty())
358 // Collect all extensions ids with absolute paths in |absolute_keys|.
359 std::set<std::string> absolute_keys;
360 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
361 const base::DictionaryValue* extension_dict = NULL;
362 if (!i.value().GetAsDictionary(&extension_dict))
365 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
366 Manifest::IsUnpackedLocation(
367 static_cast<Manifest::Location>(location_value))) {
368 // Unpacked extensions can have absolute paths.
371 base::FilePath::StringType path_string;
372 if (!extension_dict->GetString(kPrefPath, &path_string))
374 base::FilePath path(path_string);
375 if (path.IsAbsolute())
376 absolute_keys.insert(i.key());
378 if (absolute_keys.empty())
382 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
383 base::DictionaryValue* update_dict = update.Get();
384 for (std::set<std::string>::iterator i = absolute_keys.begin();
385 i != absolute_keys.end(); ++i) {
386 base::DictionaryValue* extension_dict = NULL;
387 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
388 NOTREACHED() << "Control should never reach here for extension " << *i;
391 base::FilePath::StringType path_string;
392 extension_dict->GetString(kPrefPath, &path_string);
393 base::FilePath path(path_string);
394 extension_dict->SetString(kPrefPath,
395 MakePathRelative(install_directory_, path));
399 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
400 const std::string& extension_id) const {
401 const base::DictionaryValue* extensions =
402 prefs_->GetDictionary(pref_names::kExtensions);
403 const base::DictionaryValue* extension_dict = NULL;
405 !extensions->GetDictionary(extension_id, &extension_dict)) {
408 return extension_dict;
411 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
412 const std::string& key,
413 base::Value* data_value) {
414 if (!Extension::IdIsValid(extension_id)) {
415 NOTREACHED() << "Invalid extension_id " << extension_id;
418 ScopedExtensionPrefUpdate update(prefs_, extension_id);
420 update->Set(key, data_value);
422 update->Remove(key, NULL);
425 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
426 extension_pref_value_map_->UnregisterExtension(extension_id);
427 content_settings_store_->UnregisterExtension(extension_id);
428 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
429 base::DictionaryValue* dict = update.Get();
430 dict->Remove(extension_id, NULL);
433 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
434 const std::string& pref_key,
435 bool* out_value) const {
436 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
437 if (!ext || !ext->GetBoolean(pref_key, out_value))
443 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
444 const std::string& pref_key,
445 int* out_value) const {
446 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
447 if (!ext || !ext->GetInteger(pref_key, out_value))
453 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
454 const std::string& pref_key,
455 std::string* out_value) const {
456 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
457 if (!ext || !ext->GetString(pref_key, out_value))
463 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
464 const std::string& pref_key,
465 const base::ListValue** out_value) const {
466 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
467 const base::ListValue* out = NULL;
468 if (!ext || !ext->GetList(pref_key, &out))
476 bool ExtensionPrefs::ReadPrefAsDictionary(
477 const std::string& extension_id,
478 const std::string& pref_key,
479 const base::DictionaryValue** out_value) const {
480 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
481 const base::DictionaryValue* out = NULL;
482 if (!ext || !ext->GetDictionary(pref_key, &out))
490 bool ExtensionPrefs::HasPrefForExtension(
491 const std::string& extension_id) const {
492 return GetExtensionPref(extension_id) != NULL;
495 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
496 const std::string& pref_key,
497 URLPatternSet* result,
499 const base::ListValue* value = NULL;
500 if (!ReadPrefAsList(extension_id, pref_key, &value))
503 bool allow_file_access = AllowFileAccess(extension_id);
504 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
507 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
508 const std::string& extension_id,
509 const std::string& pref_key,
510 const URLPatternSet& new_value) {
511 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
514 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
515 const std::string& extension_id,
516 const std::string& pref_key) const {
517 bool out_value = false;
518 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
521 PermissionSet* ExtensionPrefs::ReadPrefAsPermissionSet(
522 const std::string& extension_id,
523 const std::string& pref_key) {
524 if (!GetExtensionPref(extension_id))
527 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
528 // for api_values format.
529 APIPermissionSet apis;
530 const base::ListValue* api_values = NULL;
531 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
532 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
533 APIPermissionSet::ParseFromJSON(api_values,
534 APIPermissionSet::kAllowInternalPermissions,
538 // Retrieve the Manifest Keys permissions. Please refer to
539 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
540 ManifestPermissionSet manifest_permissions;
541 const base::ListValue* manifest_permissions_values = NULL;
542 std::string manifest_permission_pref =
543 JoinPrefs(pref_key, kPrefManifestPermissions);
544 if (ReadPrefAsList(extension_id, manifest_permission_pref,
545 &manifest_permissions_values)) {
546 ManifestPermissionSet::ParseFromJSON(
547 manifest_permissions_values, &manifest_permissions, NULL, NULL);
550 // Retrieve the explicit host permissions.
551 URLPatternSet explicit_hosts;
552 ReadPrefAsURLPatternSet(
553 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
554 &explicit_hosts, Extension::kValidHostPermissionSchemes);
556 // Retrieve the scriptable host permissions.
557 URLPatternSet scriptable_hosts;
558 ReadPrefAsURLPatternSet(
559 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
560 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
562 return new PermissionSet(
563 apis, manifest_permissions, explicit_hosts, scriptable_hosts);
566 // Set the API or Manifest permissions.
567 // The format of api_values is:
568 // [ "permission_name1", // permissions do not support detail.
569 // "permission_name2",
570 // {"permission_name3": value },
571 // // permission supports detail, permission detail will be stored in value.
575 static base::ListValue* CreatePermissionList(const T& permissions) {
576 base::ListValue* values = new base::ListValue();
577 for (typename T::const_iterator i = permissions.begin();
578 i != permissions.end(); ++i) {
579 scoped_ptr<base::Value> detail(i->ToValue());
581 base::DictionaryValue* tmp = new base::DictionaryValue();
582 tmp->Set(i->name(), detail.release());
585 values->Append(new base::StringValue(i->name()));
591 void ExtensionPrefs::SetExtensionPrefPermissionSet(
592 const std::string& extension_id,
593 const std::string& pref_key,
594 const PermissionSet* new_value) {
595 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
596 base::ListValue* api_values = CreatePermissionList(new_value->apis());
597 UpdateExtensionPref(extension_id, api_pref, api_values);
599 std::string manifest_permissions_pref =
600 JoinPrefs(pref_key, kPrefManifestPermissions);
601 base::ListValue* manifest_permissions_values = CreatePermissionList(
602 new_value->manifest_permissions());
603 UpdateExtensionPref(extension_id,
604 manifest_permissions_pref,
605 manifest_permissions_values);
607 // Set the explicit host permissions.
608 if (!new_value->explicit_hosts().is_empty()) {
609 SetExtensionPrefURLPatternSet(extension_id,
610 JoinPrefs(pref_key, kPrefExplicitHosts),
611 new_value->explicit_hosts());
614 // Set the scriptable host permissions.
615 if (!new_value->scriptable_hosts().is_empty()) {
616 SetExtensionPrefURLPatternSet(extension_id,
617 JoinPrefs(pref_key, kPrefScriptableHosts),
618 new_value->scriptable_hosts());
622 int ExtensionPrefs::IncrementAcknowledgePromptCount(
623 const std::string& extension_id) {
625 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
627 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
628 new base::FundamentalValue(count));
632 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
633 const std::string& extension_id) {
634 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
637 void ExtensionPrefs::AcknowledgeExternalExtension(
638 const std::string& extension_id) {
639 DCHECK(Extension::IdIsValid(extension_id));
640 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
641 new base::FundamentalValue(true));
642 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
645 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
646 const std::string& extension_id) {
647 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
650 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
651 const std::string& extension_id) {
652 DCHECK(Extension::IdIsValid(extension_id));
653 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
654 new base::FundamentalValue(true));
655 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
658 bool ExtensionPrefs::IsExternalInstallFirstRun(
659 const std::string& extension_id) {
660 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
663 void ExtensionPrefs::SetExternalInstallFirstRun(
664 const std::string& extension_id) {
665 DCHECK(Extension::IdIsValid(extension_id));
666 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
667 new base::FundamentalValue(true));
670 bool ExtensionPrefs::HasWipeoutBeenAcknowledged(
671 const std::string& extension_id) {
672 return ReadPrefAsBooleanAndReturn(extension_id, kPrefWipeoutAcknowledged);
675 void ExtensionPrefs::SetWipeoutAcknowledged(
676 const std::string& extension_id,
678 UpdateExtensionPref(extension_id, kPrefWipeoutAcknowledged,
679 value ? base::Value::CreateBooleanValue(value) : NULL);
682 bool ExtensionPrefs::SetAlertSystemFirstRun() {
683 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
686 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
690 bool ExtensionPrefs::ExtensionsBlacklistedByDefault() const {
691 return admin_policy::BlacklistedByDefault(
692 prefs_->GetList(pref_names::kInstallDenyList));
695 bool ExtensionPrefs::DidExtensionEscalatePermissions(
696 const std::string& extension_id) {
697 return ReadPrefAsBooleanAndReturn(extension_id,
698 kExtensionDidEscalatePermissions);
701 void ExtensionPrefs::SetDidExtensionEscalatePermissions(
702 const Extension* extension, bool did_escalate) {
703 UpdateExtensionPref(extension->id(), kExtensionDidEscalatePermissions,
704 new base::FundamentalValue(did_escalate));
707 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
709 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
713 return Extension::DISABLE_NONE;
716 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
717 Extension::DisableReason disable_reason) {
718 int new_value = GetDisableReasons(extension_id) |
719 static_cast<int>(disable_reason);
720 UpdateExtensionPref(extension_id, kPrefDisableReasons,
721 new base::FundamentalValue(new_value));
724 void ExtensionPrefs::RemoveDisableReason(
725 const std::string& extension_id,
726 Extension::DisableReason disable_reason) {
727 int new_value = GetDisableReasons(extension_id) &
728 ~static_cast<int>(disable_reason);
729 if (new_value == Extension::DISABLE_NONE) {
730 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
732 UpdateExtensionPref(extension_id, kPrefDisableReasons,
733 new base::FundamentalValue(new_value));
737 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
738 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
741 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() {
742 std::set<std::string> ids;
744 const base::DictionaryValue* extensions =
745 prefs_->GetDictionary(pref_names::kExtensions);
749 for (base::DictionaryValue::Iterator it(*extensions);
750 !it.IsAtEnd(); it.Advance()) {
751 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
752 NOTREACHED() << "Invalid pref for extension " << it.key();
755 if (IsBlacklistBitSet(
756 static_cast<const base::DictionaryValue*>(&it.value()))) {
757 ids.insert(it.key());
764 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
765 bool is_blacklisted) {
766 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
767 if (is_blacklisted == currently_blacklisted)
770 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
772 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
774 if (is_blacklisted) {
775 UpdateExtensionPref(extension_id,
777 new base::FundamentalValue(true));
779 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
780 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
781 if (dict && dict->empty())
782 DeleteExtensionPrefs(extension_id);
786 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
787 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
788 return ext_prefs && IsBlacklistBitSet(ext_prefs);
793 // Serializes |time| as a string value mapped to |key| in |dictionary|.
794 void SaveTime(base::DictionaryValue* dictionary,
796 const base::Time& time) {
799 std::string string_value = base::Int64ToString(time.ToInternalValue());
800 dictionary->SetString(key, string_value);
803 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
804 // (is_null() will return true).
805 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
808 std::string string_value;
810 if (dictionary->GetString(key, &string_value)) {
811 if (base::StringToInt64(string_value, &value)) {
812 return base::Time::FromInternalValue(value);
820 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
821 DCHECK(Extension::IdIsValid(extension_id));
822 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
825 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
826 const base::Time& time) {
827 DCHECK(Extension::IdIsValid(extension_id));
828 ScopedExtensionPrefUpdate update(prefs_, extension_id);
829 SaveTime(update.Get(), kLastPingDay, time);
832 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
833 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
837 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
838 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
839 SaveTime(update.Get(), kLastPingDay, time);
842 base::Time ExtensionPrefs::LastActivePingDay(const std::string& extension_id) {
843 DCHECK(Extension::IdIsValid(extension_id));
844 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
847 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
848 const base::Time& time) {
849 DCHECK(Extension::IdIsValid(extension_id));
850 ScopedExtensionPrefUpdate update(prefs_, extension_id);
851 SaveTime(update.Get(), kLastActivePingDay, time);
854 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) {
855 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
857 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
862 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
864 UpdateExtensionPref(extension_id, kActiveBit,
865 new base::FundamentalValue(active));
868 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
869 PermissionsInfo* info = PermissionsInfo::GetInstance();
870 for (ExtensionIdList::const_iterator ext_id =
871 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
872 // An extension's granted permissions need to be migrated if the
873 // full_access bit is present. This bit was always present in the previous
874 // scheme and is never present now.
876 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
877 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
880 // Remove the full access bit (empty list will get trimmed).
882 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
884 // Add the plugin permission if the full access bit was set.
886 const base::ListValue* apis = NULL;
887 base::ListValue* new_apis = NULL;
889 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
890 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
891 new_apis = apis->DeepCopy();
893 new_apis = new base::ListValue();
895 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
896 new_apis->Append(new base::StringValue(plugin_name));
897 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
900 // The granted permissions originally only held the effective hosts,
901 // which are a combination of host and user script host permissions.
902 // We now maintain these lists separately. For migration purposes, it
903 // does not matter how we treat the old effective hosts as long as the
904 // new effective hosts will be the same, so we move them to explicit
906 const base::ListValue* hosts = NULL;
907 std::string explicit_hosts =
908 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
909 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
911 *ext_id, explicit_hosts, hosts->DeepCopy());
913 // We can get rid of the old one by setting it to an empty list.
914 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
919 void ExtensionPrefs::MigrateDisableReasons(
920 const ExtensionIdList& extension_ids) {
921 for (ExtensionIdList::const_iterator ext_id =
922 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
924 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
925 int new_value = Extension::DISABLE_NONE;
927 case Extension::DEPRECATED_DISABLE_USER_ACTION:
928 new_value = Extension::DISABLE_USER_ACTION;
930 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
931 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
933 case Extension::DEPRECATED_DISABLE_RELOAD:
934 new_value = Extension::DISABLE_RELOAD;
938 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
939 new base::FundamentalValue(new_value));
940 // Remove the old disable reason.
941 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
946 PermissionSet* ExtensionPrefs::GetGrantedPermissions(
947 const std::string& extension_id) {
948 CHECK(Extension::IdIsValid(extension_id));
949 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
952 void ExtensionPrefs::AddGrantedPermissions(
953 const std::string& extension_id,
954 const PermissionSet* permissions) {
955 CHECK(Extension::IdIsValid(extension_id));
957 scoped_refptr<PermissionSet> granted_permissions(
958 GetGrantedPermissions(extension_id));
960 // The new granted permissions are the union of the already granted
961 // permissions and the newly granted permissions.
962 scoped_refptr<PermissionSet> new_perms(
963 PermissionSet::CreateUnion(
964 permissions, granted_permissions.get()));
966 SetExtensionPrefPermissionSet(
967 extension_id, kPrefGrantedPermissions, new_perms.get());
970 void ExtensionPrefs::RemoveGrantedPermissions(
971 const std::string& extension_id,
972 const PermissionSet* permissions) {
973 CHECK(Extension::IdIsValid(extension_id));
975 scoped_refptr<PermissionSet> granted_permissions(
976 GetGrantedPermissions(extension_id));
978 // The new granted permissions are the difference of the already granted
979 // permissions and the newly ungranted permissions.
980 scoped_refptr<PermissionSet> new_perms(
981 PermissionSet::CreateDifference(
982 granted_permissions.get(), permissions));
984 SetExtensionPrefPermissionSet(
985 extension_id, kPrefGrantedPermissions, new_perms.get());
988 PermissionSet* ExtensionPrefs::GetActivePermissions(
989 const std::string& extension_id) {
990 CHECK(Extension::IdIsValid(extension_id));
991 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
994 void ExtensionPrefs::SetActivePermissions(
995 const std::string& extension_id,
996 const PermissionSet* permissions) {
997 SetExtensionPrefPermissionSet(
998 extension_id, kPrefActivePermissions, permissions);
1001 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1003 base::Value* value = new base::FundamentalValue(is_running);
1004 UpdateExtensionPref(extension_id, kPrefRunning, value);
1007 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) {
1008 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1011 bool running = false;
1012 extension->GetBoolean(kPrefRunning, &running);
1016 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1018 base::Value* value = new base::FundamentalValue(is_active);
1019 UpdateExtensionPref(extension_id, kIsActive, value);
1022 bool ExtensionPrefs::IsActive(const std::string& extension_id) {
1023 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1026 bool is_active = false;
1027 extension->GetBoolean(kIsActive, &is_active);
1031 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1032 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1035 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1037 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1038 new base::FundamentalValue(enabled));
1041 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1042 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1045 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1047 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1048 new base::FundamentalValue(allow));
1051 bool ExtensionPrefs::HasAllowFileAccessSetting(
1052 const std::string& extension_id) const {
1053 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1054 return ext && ext->HasKey(kPrefAllowFileAccess);
1057 bool ExtensionPrefs::DoesExtensionHaveState(
1058 const std::string& id, Extension::State check_state) const {
1059 const base::DictionaryValue* extension = GetExtensionPref(id);
1061 if (!extension || !extension->GetInteger(kPrefState, &state))
1064 if (state < 0 || state >= Extension::NUM_STATES) {
1065 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1069 return state == check_state;
1072 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1073 const std::string& id) const {
1074 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1077 bool ExtensionPrefs::IsExtensionDisabled(
1078 const std::string& id) const {
1079 return DoesExtensionHaveState(id, Extension::DISABLED);
1082 ExtensionIdList ExtensionPrefs::GetToolbarOrder() {
1083 ExtensionIdList id_list_out;
1084 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1088 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1089 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1092 bool ExtensionPrefs::GetKnownDisabled(ExtensionIdSet* id_set_out) {
1093 return GetUserExtensionPrefIntoContainer(pref_names::kKnownDisabled,
1097 void ExtensionPrefs::SetKnownDisabled(const ExtensionIdSet& extension_ids) {
1098 SetExtensionPrefFromContainer(pref_names::kKnownDisabled, extension_ids);
1101 void ExtensionPrefs::OnExtensionInstalled(
1102 const Extension* extension,
1103 Extension::State initial_state,
1104 bool blacklisted_for_malware,
1105 const syncer::StringOrdinal& page_ordinal) {
1106 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1107 base::DictionaryValue* extension_dict = update.Get();
1108 const base::Time install_time = time_provider_->GetCurrentTime();
1109 PopulateExtensionInfoPrefs(extension, install_time, initial_state,
1110 blacklisted_for_malware, extension_dict);
1111 FinishExtensionInfoPrefs(extension->id(), install_time,
1112 extension->RequiresSortOrdinal(),
1113 page_ordinal, extension_dict);
1116 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1117 const Manifest::Location& location,
1118 bool external_uninstall) {
1119 app_sorting_->ClearOrdinals(extension_id);
1121 // For external extensions, we save a preference reminding ourself not to try
1122 // and install the extension anymore (except when |external_uninstall| is
1123 // true, which signifies that the registry key was deleted or the pref file
1124 // no longer lists the extension).
1125 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1126 UpdateExtensionPref(extension_id, kPrefState,
1127 new base::FundamentalValue(
1128 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1129 extension_pref_value_map_->SetExtensionState(extension_id, false);
1130 content_settings_store_->SetExtensionState(extension_id, false);
1132 DeleteExtensionPrefs(extension_id);
1136 void ExtensionPrefs::SetExtensionState(const std::string& extension_id,
1137 Extension::State state) {
1138 UpdateExtensionPref(extension_id, kPrefState,
1139 new base::FundamentalValue(state));
1140 bool enabled = (state == Extension::ENABLED);
1141 extension_pref_value_map_->SetExtensionState(extension_id, enabled);
1142 content_settings_store_->SetExtensionState(extension_id, enabled);
1145 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1146 BlacklistState state) {
1147 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1148 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1149 new base::FundamentalValue(state));
1152 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1153 const std::string& extension_id) {
1154 if (IsExtensionBlacklisted(extension_id))
1155 return BLACKLISTED_MALWARE;
1156 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1158 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1159 return static_cast<BlacklistState>(int_value);
1161 return NOT_BLACKLISTED;
1164 std::string ExtensionPrefs::GetVersionString(const std::string& extension_id) {
1165 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1167 return std::string();
1169 std::string version;
1170 extension->GetString(kPrefVersion, &version);
1175 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1176 if (!Manifest::IsUnpackedLocation(extension->location())) {
1177 const base::DictionaryValue* extension_dict =
1178 GetExtensionPref(extension->id());
1179 if (!extension_dict)
1181 const base::DictionaryValue* old_manifest = NULL;
1182 bool update_required =
1183 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1184 !extension->manifest()->value()->Equals(old_manifest);
1185 if (update_required) {
1186 UpdateExtensionPref(extension->id(), kPrefManifest,
1187 extension->manifest()->value()->DeepCopy());
1192 base::FilePath ExtensionPrefs::GetExtensionPath(
1193 const std::string& extension_id) {
1194 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
1196 return base::FilePath();
1199 if (!dict->GetString(kPrefPath, &path))
1200 return base::FilePath();
1202 return install_directory_.Append(base::FilePath::FromUTF8Unsafe(path));
1205 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1206 const std::string& extension_id,
1207 const base::DictionaryValue* extension) const {
1209 if (!extension->GetInteger(kPrefLocation, &location_value))
1210 return scoped_ptr<ExtensionInfo>();
1212 base::FilePath::StringType path;
1213 if (!extension->GetString(kPrefPath, &path))
1214 return scoped_ptr<ExtensionInfo>();
1216 // Make path absolute. Unpacked extensions will already have absolute paths,
1217 // otherwise make it so.
1218 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1219 if (!Manifest::IsUnpackedLocation(location)) {
1220 DCHECK(location == Manifest::COMPONENT ||
1221 !base::FilePath(path).IsAbsolute());
1222 path = install_directory_.Append(path).value();
1225 // Only the following extension types have data saved in the preferences.
1226 if (location != Manifest::INTERNAL &&
1227 !Manifest::IsUnpackedLocation(location) &&
1228 !Manifest::IsExternalLocation(location)) {
1230 return scoped_ptr<ExtensionInfo>();
1233 const base::DictionaryValue* manifest = NULL;
1234 if (!Manifest::IsUnpackedLocation(location) &&
1235 !extension->GetDictionary(kPrefManifest, &manifest)) {
1236 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1237 // Just a warning for now.
1240 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1241 manifest, extension_id, base::FilePath(path), location));
1244 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1245 const std::string& extension_id) const {
1246 const base::DictionaryValue* ext = NULL;
1247 const base::DictionaryValue* extensions =
1248 prefs_->GetDictionary(pref_names::kExtensions);
1250 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1251 return scoped_ptr<ExtensionInfo>();
1253 if (!ext->GetInteger(kPrefState, &state_value) ||
1254 state_value == Extension::ENABLED_COMPONENT) {
1255 // Old preferences files may not have kPrefState for component extensions.
1256 return scoped_ptr<ExtensionInfo>();
1259 if (state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1260 LOG(WARNING) << "External extension with id " << extension_id
1261 << " has been uninstalled by the user";
1262 return scoped_ptr<ExtensionInfo>();
1265 return GetInstalledInfoHelper(extension_id, ext);
1268 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1269 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1270 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1272 const base::DictionaryValue* extensions =
1273 prefs_->GetDictionary(pref_names::kExtensions);
1274 for (base::DictionaryValue::Iterator extension_id(*extensions);
1275 !extension_id.IsAtEnd(); extension_id.Advance()) {
1276 if (!Extension::IdIsValid(extension_id.key()))
1279 scoped_ptr<ExtensionInfo> info =
1280 GetInstalledExtensionInfo(extension_id.key());
1282 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1285 return extensions_info.Pass();
1288 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1289 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1290 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1292 const base::DictionaryValue* extensions =
1293 prefs_->GetDictionary(pref_names::kExtensions);
1294 for (base::DictionaryValue::Iterator extension_id(*extensions);
1295 !extension_id.IsAtEnd(); extension_id.Advance()) {
1296 const base::DictionaryValue* ext = NULL;
1297 if (!Extension::IdIsValid(extension_id.key()) ||
1298 !IsExternalExtensionUninstalled(extension_id.key()) ||
1299 !extension_id.value().GetAsDictionary(&ext))
1302 scoped_ptr<ExtensionInfo> info =
1303 GetInstalledInfoHelper(extension_id.key(), ext);
1305 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1308 return extensions_info.Pass();
1311 void ExtensionPrefs::SetDelayedInstallInfo(
1312 const Extension* extension,
1313 Extension::State initial_state,
1314 bool blacklisted_for_malware,
1315 DelayReason delay_reason,
1316 const syncer::StringOrdinal& page_ordinal) {
1317 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1318 PopulateExtensionInfoPrefs(extension, time_provider_->GetCurrentTime(),
1319 initial_state, blacklisted_for_malware,
1322 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1323 // should not be in the final extension prefs. All entries here should have
1324 // a corresponding Remove() call in FinishDelayedInstallInfo().
1325 if (extension->RequiresSortOrdinal()) {
1326 extension_dict->SetString(
1327 kPrefSuggestedPageOrdinal,
1328 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1331 extension_dict->SetInteger(kDelayedInstallReason,
1332 static_cast<int>(delay_reason));
1334 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1337 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1338 const std::string& extension_id) {
1339 if (!GetExtensionPref(extension_id))
1341 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1342 bool result = update->Remove(kDelayedInstallInfo, NULL);
1346 bool ExtensionPrefs::FinishDelayedInstallInfo(
1347 const std::string& extension_id) {
1348 CHECK(Extension::IdIsValid(extension_id));
1349 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1350 base::DictionaryValue* extension_dict = update.Get();
1351 base::DictionaryValue* pending_install_dict = NULL;
1352 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1353 &pending_install_dict)) {
1357 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1358 // Also do any other data cleanup that makes sense.
1359 std::string serialized_ordinal;
1360 syncer::StringOrdinal suggested_page_ordinal;
1361 bool needs_sort_ordinal = false;
1362 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1363 &serialized_ordinal)) {
1364 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1365 needs_sort_ordinal = true;
1366 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1368 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1370 const base::Time install_time = time_provider_->GetCurrentTime();
1371 pending_install_dict->Set(
1373 new base::StringValue(
1374 base::Int64ToString(install_time.ToInternalValue())));
1376 // Commit the delayed install data.
1377 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1379 extension_dict->Set(it.key(), it.value().DeepCopy());
1381 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1382 suggested_page_ordinal, extension_dict);
1386 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1387 const std::string& extension_id) const {
1388 const base::DictionaryValue* extension_prefs =
1389 GetExtensionPref(extension_id);
1390 if (!extension_prefs)
1391 return scoped_ptr<ExtensionInfo>();
1393 const base::DictionaryValue* ext = NULL;
1394 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1395 return scoped_ptr<ExtensionInfo>();
1397 return GetInstalledInfoHelper(extension_id, ext);
1400 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1401 const std::string& extension_id) const {
1402 const base::DictionaryValue* extension_prefs =
1403 GetExtensionPref(extension_id);
1404 if (!extension_prefs)
1405 return DELAY_REASON_NONE;
1407 const base::DictionaryValue* ext = NULL;
1408 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1409 return DELAY_REASON_NONE;
1412 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1413 return DELAY_REASON_NONE;
1415 return static_cast<DelayReason>(delay_reason);
1418 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1419 GetAllDelayedInstallInfo() const {
1420 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1422 const base::DictionaryValue* extensions =
1423 prefs_->GetDictionary(pref_names::kExtensions);
1424 for (base::DictionaryValue::Iterator extension_id(*extensions);
1425 !extension_id.IsAtEnd(); extension_id.Advance()) {
1426 if (!Extension::IdIsValid(extension_id.key()))
1429 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1431 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1434 return extensions_info.Pass();
1437 bool ExtensionPrefs::WasAppDraggedByUser(const std::string& extension_id) {
1438 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1441 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1442 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1443 new base::FundamentalValue(true));
1446 bool ExtensionPrefs::IsFromWebStore(
1447 const std::string& extension_id) const {
1448 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1449 bool result = false;
1450 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1455 bool ExtensionPrefs::IsFromBookmark(
1456 const std::string& extension_id) const {
1457 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1458 bool result = false;
1459 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1464 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1465 int creation_flags = Extension::NO_FLAGS;
1466 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1467 // Since kPrefCreationFlags was added later, it will be missing for
1468 // previously installed extensions.
1469 if (IsFromBookmark(extension_id))
1470 creation_flags |= Extension::FROM_BOOKMARK;
1471 if (IsFromWebStore(extension_id))
1472 creation_flags |= Extension::FROM_WEBSTORE;
1473 if (WasInstalledByDefault(extension_id))
1474 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1476 return creation_flags;
1479 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1480 const std::string& extension_id) const {
1481 int creation_flags = Extension::NO_FLAGS;
1482 const base::DictionaryValue* delayed_info = NULL;
1483 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1484 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1486 return creation_flags;
1489 bool ExtensionPrefs::WasInstalledByDefault(
1490 const std::string& extension_id) const {
1491 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1492 bool result = false;
1494 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1499 base::Time ExtensionPrefs::GetInstallTime(
1500 const std::string& extension_id) const {
1501 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1504 return base::Time();
1506 std::string install_time_str;
1507 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1508 return base::Time();
1509 int64 install_time_i64 = 0;
1510 if (!base::StringToInt64(install_time_str, &install_time_i64))
1511 return base::Time();
1512 return base::Time::FromInternalValue(install_time_i64);
1515 base::Time ExtensionPrefs::GetLastLaunchTime(
1516 const std::string& extension_id) const {
1517 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1519 return base::Time();
1521 std::string launch_time_str;
1522 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1523 return base::Time();
1524 int64 launch_time_i64 = 0;
1525 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1526 return base::Time();
1527 return base::Time::FromInternalValue(launch_time_i64);
1530 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1531 const base::Time& time) {
1532 DCHECK(Extension::IdIsValid(extension_id));
1533 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1534 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1537 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) {
1540 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1542 for (size_t i = 0; i < extensions_info->size(); ++i) {
1543 ExtensionInfo* info = extensions_info->at(i).get();
1544 out->push_back(info->extension_id);
1549 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1550 const PrefService* pref_service) {
1551 ExtensionIdList result;
1553 const base::DictionaryValue* extension_prefs = NULL;
1554 const base::Value* extension_prefs_value =
1555 pref_service->GetUserPrefValue(pref_names::kExtensions);
1556 if (!extension_prefs_value ||
1557 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1558 return result; // Empty set
1561 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1563 const base::DictionaryValue* ext = NULL;
1564 if (!it.value().GetAsDictionary(&ext)) {
1565 NOTREACHED() << "Invalid pref for extension " << it.key();
1568 if (!IsBlacklistBitSet(ext))
1569 result.push_back(it.key());
1574 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1575 // Fix old entries that did not get an installation time entry when they
1576 // were installed or don't have a preferences field.
1577 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1578 ext_id != extension_ids.end(); ++ext_id) {
1579 if (GetInstallTime(*ext_id) == base::Time()) {
1580 VLOG(1) << "Could not parse installation time of extension "
1581 << *ext_id << ". It was probably installed before setting "
1582 << kPrefInstallTime << " was introduced. Updating "
1583 << kPrefInstallTime << " to the current time.";
1584 const base::Time install_time = time_provider_->GetCurrentTime();
1585 UpdateExtensionPref(*ext_id,
1587 new base::StringValue(base::Int64ToString(
1588 install_time.ToInternalValue())));
1593 void ExtensionPrefs::InitPrefStore() {
1594 if (extensions_disabled_) {
1595 extension_pref_value_map_->NotifyInitializationCompleted();
1599 // When this is called, the PrefService is initialized and provides access
1600 // to the user preferences stored in a JSON file.
1601 ExtensionIdList extension_ids;
1602 GetExtensions(&extension_ids);
1603 // Create empty preferences dictionary for each extension (these dictionaries
1604 // are pruned when persisting the preferences to disk).
1605 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1606 ext_id != extension_ids.end(); ++ext_id) {
1607 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1608 // This creates an empty dictionary if none is stored.
1612 FixMissingPrefs(extension_ids);
1613 MigratePermissions(extension_ids);
1614 MigrateDisableReasons(extension_ids);
1615 app_sorting_->Initialize(extension_ids);
1617 PreferenceAPI::InitExtensionControlledPrefs(this, extension_pref_value_map_);
1619 extension_pref_value_map_->NotifyInitializationCompleted();
1622 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) {
1623 bool has_incognito_pref_value = false;
1624 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1626 &has_incognito_pref_value);
1627 return has_incognito_pref_value;
1630 URLPatternSet ExtensionPrefs::GetAllowedInstallSites() {
1631 URLPatternSet result;
1632 const base::ListValue* list =
1633 prefs_->GetList(pref_names::kAllowedInstallSites);
1636 for (size_t i = 0; i < list->GetSize(); ++i) {
1637 std::string entry_string;
1638 URLPattern entry(URLPattern::SCHEME_ALL);
1639 if (!list->GetString(i, &entry_string) ||
1640 entry.Parse(entry_string) != URLPattern::PARSE_SUCCESS) {
1641 LOG(ERROR) << "Invalid value for preference: "
1642 << pref_names::kAllowedInstallSites << "." << i;
1645 result.AddPattern(entry);
1651 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1652 const std::string& extension_id) const {
1653 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1654 if (!extension_prefs)
1657 const base::DictionaryValue* ext = NULL;
1658 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1664 void ExtensionPrefs::SetGeometryCache(
1665 const std::string& extension_id,
1666 scoped_ptr<base::DictionaryValue> cache) {
1667 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1670 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() {
1671 return prefs_->GetDictionary(kInstallSignature);
1674 void ExtensionPrefs::SetInstallSignature(
1675 const base::DictionaryValue* signature) {
1677 prefs_->Set(kInstallSignature, *signature);
1678 DVLOG(1) << "SetInstallSignature - saving";
1680 DVLOG(1) << "SetInstallSignature - clearing";
1681 prefs_->ClearPref(kInstallSignature);
1686 ExtensionPrefs::ExtensionPrefs(
1688 const base::FilePath& root_dir,
1689 ExtensionPrefValueMap* extension_pref_value_map,
1690 scoped_ptr<AppSorting> app_sorting,
1691 scoped_ptr<TimeProvider> time_provider,
1692 bool extensions_disabled)
1694 install_directory_(root_dir),
1695 extension_pref_value_map_(extension_pref_value_map),
1696 app_sorting_(app_sorting.Pass()),
1697 content_settings_store_(new ContentSettingsStore()),
1698 time_provider_(time_provider.Pass()),
1699 extensions_disabled_(extensions_disabled) {
1700 app_sorting_->SetExtensionScopedPrefs(this);
1701 MakePathsRelative();
1705 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1706 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1709 bool ExtensionPrefs::NeedsStorageGarbageCollection() {
1710 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1714 void ExtensionPrefs::RegisterProfilePrefs(
1715 user_prefs::PrefRegistrySyncable* registry) {
1716 registry->RegisterDictionaryPref(
1717 pref_names::kExtensions,
1718 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1719 registry->RegisterListPref(pref_names::kToolbar,
1720 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1721 registry->RegisterIntegerPref(
1722 pref_names::kToolbarSize,
1723 -1, // default value
1724 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1725 registry->RegisterDictionaryPref(
1726 kExtensionsBlacklistUpdate,
1727 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1728 registry->RegisterListPref(pref_names::kInstallAllowList,
1729 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1730 registry->RegisterListPref(pref_names::kInstallDenyList,
1731 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1732 registry->RegisterDictionaryPref(
1733 pref_names::kInstallForceList,
1734 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1735 registry->RegisterListPref(pref_names::kAllowedTypes,
1736 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1737 registry->RegisterBooleanPref(
1738 pref_names::kStorageGarbageCollect,
1739 false, // default value
1740 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1741 registry->RegisterInt64Pref(
1742 pref_names::kLastUpdateCheck,
1744 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1745 registry->RegisterInt64Pref(
1746 pref_names::kNextUpdateCheck,
1748 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1749 registry->RegisterListPref(pref_names::kAllowedInstallSites,
1750 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1751 registry->RegisterStringPref(
1752 pref_names::kLastChromeVersion,
1753 std::string(), // default value
1754 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1755 registry->RegisterListPref(pref_names::kKnownDisabled,
1756 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1757 #if defined(TOOLKIT_VIEWS)
1758 registry->RegisterIntegerPref(
1759 pref_names::kBrowserActionContainerWidth,
1761 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1763 registry->RegisterDictionaryPref(
1765 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1767 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist,
1768 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1769 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist,
1770 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1771 registry->RegisterBooleanPref(
1772 pref_names::kNativeMessagingUserLevelHosts,
1773 true, // default value
1774 user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
1777 template <class ExtensionIdContainer>
1778 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1780 ExtensionIdContainer* id_container_out) {
1781 DCHECK(id_container_out->empty());
1783 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1784 const base::ListValue* user_pref_as_list;
1785 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1788 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1789 *id_container_out, id_container_out->end());
1790 std::string extension_id;
1791 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1792 value_it != user_pref_as_list->end(); ++value_it) {
1793 if (!(*value_it)->GetAsString(&extension_id)) {
1797 insert_iterator = extension_id;
1802 template <class ExtensionIdContainer>
1803 void ExtensionPrefs::SetExtensionPrefFromContainer(
1805 const ExtensionIdContainer& strings) {
1806 ListPrefUpdate update(prefs_, pref);
1807 base::ListValue* list_of_values = update.Get();
1808 list_of_values->Clear();
1809 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1810 iter != strings.end(); ++iter) {
1811 list_of_values->Append(new base::StringValue(*iter));
1815 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1816 const Extension* extension,
1817 const base::Time install_time,
1818 Extension::State initial_state,
1819 bool blacklisted_for_malware,
1820 base::DictionaryValue* extension_dict) {
1821 // Leave the state blank for component extensions so that old chrome versions
1822 // loading new profiles do not fail in GetInstalledExtensionInfo. Older
1823 // Chrome versions would only check for an omitted state.
1824 if (initial_state != Extension::ENABLED_COMPONENT)
1825 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1827 extension_dict->Set(kPrefLocation,
1828 new base::FundamentalValue(extension->location()));
1829 extension_dict->Set(kPrefCreationFlags,
1830 new base::FundamentalValue(extension->creation_flags()));
1831 extension_dict->Set(kPrefFromWebStore,
1832 new base::FundamentalValue(extension->from_webstore()));
1833 extension_dict->Set(kPrefFromBookmark,
1834 new base::FundamentalValue(extension->from_bookmark()));
1835 extension_dict->Set(
1836 kPrefWasInstalledByDefault,
1837 new base::FundamentalValue(extension->was_installed_by_default()));
1838 extension_dict->Set(kPrefInstallTime,
1839 new base::StringValue(
1840 base::Int64ToString(install_time.ToInternalValue())));
1841 if (blacklisted_for_malware)
1842 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1844 base::FilePath::StringType path = MakePathRelative(install_directory_,
1846 extension_dict->Set(kPrefPath, new base::StringValue(path));
1847 // We store prefs about LOAD extensions, but don't cache their manifest
1848 // since it may change on disk.
1849 if (!Manifest::IsUnpackedLocation(extension->location())) {
1850 extension_dict->Set(kPrefManifest,
1851 extension->manifest()->value()->DeepCopy());
1855 void ExtensionPrefs::FinishExtensionInfoPrefs(
1856 const std::string& extension_id,
1857 const base::Time install_time,
1858 bool needs_sort_ordinal,
1859 const syncer::StringOrdinal& suggested_page_ordinal,
1860 base::DictionaryValue* extension_dict) {
1861 // Reinitializes various preferences with empty dictionaries.
1862 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
1863 extension_dict->Set(pref_names::kPrefPreferences,
1864 new base::DictionaryValue);
1867 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
1868 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
1869 new base::DictionaryValue);
1872 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
1873 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
1874 new base::DictionaryValue);
1877 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
1878 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
1880 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
1881 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
1882 new base::ListValue);
1885 // If this point has been reached, any pending installs should be considered
1887 extension_dict->Remove(kDelayedInstallInfo, NULL);
1889 // Clear state that may be registered from a previous install.
1890 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
1892 // FYI, all code below here races on sudden shutdown because |extension_dict|,
1893 // |app_sorting_|, |extension_pref_value_map_|, and |content_settings_store_|
1894 // are updated non-transactionally. This is probably not fixable without
1895 // nested transactional updates to pref dictionaries.
1896 if (needs_sort_ordinal)
1897 app_sorting_->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
1899 bool is_enabled = false;
1901 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
1902 is_enabled = initial_state == Extension::ENABLED;
1905 extension_pref_value_map_->RegisterExtension(extension_id, install_time,
1907 content_settings_store_->RegisterExtension(extension_id, install_time,
1911 } // namespace extensions