Roll src/third_party/WebKit f298044:aa8346d (svn 202628:202629)
[chromium-blink-merge.git] / extensions / browser / extension_prefs.cc
blobc7a5aea5122827c08f6cfa344b3e2970e9893457
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"
7 #include <iterator>
9 #include "base/metrics/histogram_macros.h"
10 #include "base/prefs/pref_service.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_util.h"
13 #include "base/trace_event/trace_event.h"
14 #include "components/crx_file/id_util.h"
15 #include "components/pref_registry/pref_registry_syncable.h"
16 #include "extensions/browser/app_sorting.h"
17 #include "extensions/browser/event_router.h"
18 #include "extensions/browser/extension_pref_store.h"
19 #include "extensions/browser/extension_prefs_factory.h"
20 #include "extensions/browser/extension_prefs_observer.h"
21 #include "extensions/browser/extension_system.h"
22 #include "extensions/browser/install_flag.h"
23 #include "extensions/browser/pref_names.h"
24 #include "extensions/common/manifest.h"
25 #include "extensions/common/permissions/permission_set.h"
26 #include "extensions/common/permissions/permissions_info.h"
27 #include "extensions/common/url_pattern.h"
28 #include "extensions/common/user_script.h"
30 namespace extensions {
32 namespace {
34 // Additional preferences keys, which are not needed by external clients.
36 // True if this extension is running. Note this preference stops getting updated
37 // during Chrome shutdown (and won't be updated on a browser crash) and so can
38 // be used at startup to determine whether the extension was running when Chrome
39 // was last terminated.
40 const char kPrefRunning[] = "running";
42 // Whether this extension had windows when it was last running.
43 const char kIsActive[] = "is_active";
45 // Where an extension was installed from. (see Manifest::Location)
46 const char kPrefLocation[] = "location";
48 // Enabled, disabled, killed, etc. (see Extension::State)
49 const char kPrefState[] = "state";
51 // The path to the current version's manifest file.
52 const char kPrefPath[] = "path";
54 // The dictionary containing the extension's manifest.
55 const char kPrefManifest[] = "manifest";
57 // The version number.
58 const char kPrefVersion[] = "manifest.version";
60 // Indicates whether an extension is blacklisted.
61 const char kPrefBlacklist[] = "blacklist";
63 // If extension is greylisted.
64 const char kPrefBlacklistState[] = "blacklist_state";
66 // The count of how many times we prompted the user to acknowledge an
67 // extension.
68 const char kPrefAcknowledgePromptCount[] = "ack_prompt_count";
70 // Indicates whether the user has acknowledged various types of extensions.
71 const char kPrefExternalAcknowledged[] = "ack_external";
72 const char kPrefBlacklistAcknowledged[] = "ack_blacklist";
74 // Indicates whether the external extension was installed during the first
75 // run of this profile.
76 const char kPrefExternalInstallFirstRun[] = "external_first_run";
78 // DO NOT USE, use kPrefDisableReasons instead.
79 // Indicates whether the extension was updated while it was disabled.
80 const char kDeprecatedPrefDisableReason[] = "disable_reason";
82 // A bitmask of all the reasons an extension is disabled.
83 const char kPrefDisableReasons[] = "disable_reasons";
85 // The key for a serialized Time value indicating the start of the day (from the
86 // server's perspective) an extension last included a "ping" parameter during
87 // its update check.
88 const char kLastPingDay[] = "lastpingday";
90 // Similar to kLastPingDay, but for "active" instead of "rollcall" pings.
91 const char kLastActivePingDay[] = "last_active_pingday";
93 // A bit we use to keep track of whether we need to do an "active" ping.
94 const char kActiveBit[] = "active_bit";
96 // Path for settings specific to blacklist update.
97 const char kExtensionsBlacklistUpdate[] = "extensions.blacklistupdate";
99 // Path for the delayed install info dictionary preference. The actual string
100 // value is a legacy artifact for when delayed installs only pertained to
101 // updates that were waiting for idle.
102 const char kDelayedInstallInfo[] = "idle_install_info";
104 // Reason why the extension's install was delayed.
105 const char kDelayedInstallReason[] = "delay_install_reason";
107 // Path for the suggested page ordinal of a delayed extension install.
108 const char kPrefSuggestedPageOrdinal[] = "suggested_page_ordinal";
110 // A preference that, if true, will allow this extension to run in incognito
111 // mode.
112 const char kPrefIncognitoEnabled[] = "incognito";
114 // A preference to control whether an extension is allowed to inject script in
115 // pages with file URLs.
116 const char kPrefAllowFileAccess[] = "newAllowFileAccess";
117 // TODO(jstritar): As part of fixing http://crbug.com/91577, we revoked all
118 // extension file access by renaming the pref. We should eventually clean up
119 // the old flag and possibly go back to that name.
120 // const char kPrefAllowFileAccessOld[] = "allowFileAccess";
122 // A preference specifying if the user dragged the app on the NTP.
123 const char kPrefUserDraggedApp[] = "user_dragged_app_ntp";
125 // Preferences that hold which permissions the user has granted the extension.
126 // We explicitly keep track of these so that extensions can contain unknown
127 // permissions, for backwards compatibility reasons, and we can still prompt
128 // the user to accept them once recognized. We store the active permission
129 // permissions because they may differ from those defined in the manifest.
130 const char kPrefActivePermissions[] = "active_permissions";
131 const char kPrefGrantedPermissions[] = "granted_permissions";
133 // The preference names for PermissionSet values.
134 const char kPrefAPIs[] = "api";
135 const char kPrefManifestPermissions[] = "manifest_permissions";
136 const char kPrefExplicitHosts[] = "explicit_host";
137 const char kPrefScriptableHosts[] = "scriptable_host";
139 // The preference names for the old granted permissions scheme.
140 const char kPrefOldGrantedFullAccess[] = "granted_permissions.full";
141 const char kPrefOldGrantedHosts[] = "granted_permissions.host";
142 const char kPrefOldGrantedAPIs[] = "granted_permissions.api";
144 // A preference that indicates when an extension was installed.
145 const char kPrefInstallTime[] = "install_time";
147 // A preference which saves the creation flags for extensions.
148 const char kPrefCreationFlags[] = "creation_flags";
150 // A preference that indicates whether the extension was installed from the
151 // Chrome Web Store.
152 const char kPrefFromWebStore[] = "from_webstore";
154 // A preference that indicates whether the extension was installed from a
155 // mock App created from a bookmark.
156 const char kPrefFromBookmark[] = "from_bookmark";
158 // A preference that indicates whether the extension was installed as a
159 // default app.
160 const char kPrefWasInstalledByDefault[] = "was_installed_by_default";
162 // A preference that indicates whether the extension was installed as an
163 // OEM app.
164 const char kPrefWasInstalledByOem[] = "was_installed_by_oem";
166 // Key for Geometry Cache preference.
167 const char kPrefGeometryCache[] = "geometry_cache";
169 // A preference that indicates when an extension is last launched.
170 const char kPrefLastLaunchTime[] = "last_launch_time";
172 // A preference indicating whether the extension is an ephemeral app.
173 const char kPrefEphemeralApp[] = "ephemeral_app";
175 // Am installation parameter bundled with an extension.
176 const char kPrefInstallParam[] = "install_parameter";
178 // A list of installed ids and a signature.
179 const char kInstallSignature[] = "extensions.install_signature";
181 // A boolean preference that indicates whether the extension should not be
182 // synced. Default value is false.
183 const char kPrefDoNotSync[] = "do_not_sync";
185 const char kCorruptedDisableCount[] = "extensions.corrupted_disable_count";
187 // A boolean preference that indicates whether the extension has local changes
188 // that need to be synced. Default value is false.
189 const char kPrefNeedsSync[] = "needs_sync";
191 // Provider of write access to a dictionary storing extension prefs.
192 class ScopedExtensionPrefUpdate : public DictionaryPrefUpdate {
193 public:
194 ScopedExtensionPrefUpdate(PrefService* service,
195 const std::string& extension_id) :
196 DictionaryPrefUpdate(service, pref_names::kExtensions),
197 extension_id_(extension_id) {}
199 ~ScopedExtensionPrefUpdate() override {}
201 // DictionaryPrefUpdate overrides:
202 base::DictionaryValue* Get() override {
203 base::DictionaryValue* dict = DictionaryPrefUpdate::Get();
204 base::DictionaryValue* extension = NULL;
205 if (!dict->GetDictionary(extension_id_, &extension)) {
206 // Extension pref does not exist, create it.
207 extension = new base::DictionaryValue();
208 dict->SetWithoutPathExpansion(extension_id_, extension);
210 return extension;
213 private:
214 const std::string extension_id_;
216 DISALLOW_COPY_AND_ASSIGN(ScopedExtensionPrefUpdate);
219 std::string JoinPrefs(const std::string& parent, const char* child) {
220 return parent + "." + child;
223 // Checks if kPrefBlacklist is set to true in the base::DictionaryValue.
224 // Return false if the value is false or kPrefBlacklist does not exist.
225 // This is used to decide if an extension is blacklisted.
226 bool IsBlacklistBitSet(const base::DictionaryValue* ext) {
227 bool bool_value;
228 return ext->GetBoolean(kPrefBlacklist, &bool_value) && bool_value;
231 void LoadExtensionControlledPrefs(ExtensionPrefs* prefs,
232 ExtensionPrefValueMap* value_map,
233 const std::string& extension_id,
234 ExtensionPrefsScope scope) {
235 std::string scope_string;
236 if (!pref_names::ScopeToPrefName(scope, &scope_string))
237 return;
238 std::string key = extension_id + "." + scope_string;
240 const base::DictionaryValue* source_dict =
241 prefs->pref_service()->GetDictionary(pref_names::kExtensions);
242 const base::DictionaryValue* preferences = NULL;
243 if (!source_dict->GetDictionary(key, &preferences))
244 return;
246 for (base::DictionaryValue::Iterator iter(*preferences); !iter.IsAtEnd();
247 iter.Advance()) {
248 value_map->SetExtensionPref(
249 extension_id, iter.key(), scope, iter.value().DeepCopy());
253 } // namespace
256 // TimeProvider
259 ExtensionPrefs::TimeProvider::TimeProvider() {
262 ExtensionPrefs::TimeProvider::~TimeProvider() {
265 base::Time ExtensionPrefs::TimeProvider::GetCurrentTime() const {
266 return base::Time::Now();
270 // ScopedUpdate
272 template <typename T, base::Value::Type type_enum_value>
273 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::ScopedUpdate(
274 ExtensionPrefs* prefs,
275 const std::string& extension_id,
276 const std::string& key)
277 : update_(prefs->pref_service(), pref_names::kExtensions),
278 extension_id_(extension_id),
279 key_(key) {
280 DCHECK(crx_file::id_util::IdIsValid(extension_id_));
283 template <typename T, base::Value::Type type_enum_value>
284 ExtensionPrefs::ScopedUpdate<T, type_enum_value>::~ScopedUpdate() {
287 template <typename T, base::Value::Type type_enum_value>
288 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Get() {
289 base::DictionaryValue* dict = update_.Get();
290 base::DictionaryValue* extension = NULL;
291 base::Value* key_value = NULL;
292 if (!dict->GetDictionary(extension_id_, &extension) ||
293 !extension->Get(key_, &key_value)) {
294 return NULL;
296 return key_value->GetType() == type_enum_value ?
297 static_cast<T*>(key_value) :
298 NULL;
301 template <typename T, base::Value::Type type_enum_value>
302 T* ExtensionPrefs::ScopedUpdate<T, type_enum_value>::Create() {
303 base::DictionaryValue* dict = update_.Get();
304 base::DictionaryValue* extension = NULL;
305 base::Value* key_value = NULL;
306 T* value_as_t = NULL;
307 if (!dict->GetDictionary(extension_id_, &extension)) {
308 extension = new base::DictionaryValue;
309 dict->SetWithoutPathExpansion(extension_id_, extension);
311 if (!extension->Get(key_, &key_value)) {
312 value_as_t = new T;
313 extension->SetWithoutPathExpansion(key_, value_as_t);
314 } else {
315 CHECK(key_value->GetType() == type_enum_value);
316 value_as_t = static_cast<T*>(key_value);
318 return value_as_t;
321 // Explicit instantiations for Dictionary and List value types.
322 template class ExtensionPrefs::ScopedUpdate<base::DictionaryValue,
323 base::Value::TYPE_DICTIONARY>;
324 template class ExtensionPrefs::ScopedUpdate<base::ListValue,
325 base::Value::TYPE_LIST>;
328 // ExtensionPrefs
331 // static
332 ExtensionPrefs* ExtensionPrefs::Create(
333 content::BrowserContext* browser_context,
334 PrefService* prefs,
335 const base::FilePath& root_dir,
336 ExtensionPrefValueMap* extension_pref_value_map,
337 bool extensions_disabled,
338 const std::vector<ExtensionPrefsObserver*>& early_observers) {
339 return ExtensionPrefs::Create(browser_context, prefs, root_dir,
340 extension_pref_value_map, extensions_disabled,
341 early_observers,
342 make_scoped_ptr(new TimeProvider()));
345 // static
346 ExtensionPrefs* ExtensionPrefs::Create(
347 content::BrowserContext* browser_context,
348 PrefService* pref_service,
349 const base::FilePath& root_dir,
350 ExtensionPrefValueMap* extension_pref_value_map,
351 bool extensions_disabled,
352 const std::vector<ExtensionPrefsObserver*>& early_observers,
353 scoped_ptr<TimeProvider> time_provider) {
354 return new ExtensionPrefs(browser_context, pref_service, root_dir,
355 extension_pref_value_map, time_provider.Pass(),
356 extensions_disabled, early_observers);
359 ExtensionPrefs::~ExtensionPrefs() {
362 // static
363 ExtensionPrefs* ExtensionPrefs::Get(content::BrowserContext* context) {
364 return ExtensionPrefsFactory::GetInstance()->GetForBrowserContext(context);
367 static base::FilePath::StringType MakePathRelative(const base::FilePath& parent,
368 const base::FilePath& child) {
369 if (!parent.IsParent(child))
370 return child.value();
372 base::FilePath::StringType retval = child.value().substr(
373 parent.value().length());
374 if (base::FilePath::IsSeparator(retval[0]))
375 return retval.substr(1);
376 else
377 return retval;
380 void ExtensionPrefs::MakePathsRelative() {
381 const base::DictionaryValue* dict =
382 prefs_->GetDictionary(pref_names::kExtensions);
383 if (!dict || dict->empty())
384 return;
386 // Collect all extensions ids with absolute paths in |absolute_keys|.
387 std::set<std::string> absolute_keys;
388 for (base::DictionaryValue::Iterator i(*dict); !i.IsAtEnd(); i.Advance()) {
389 const base::DictionaryValue* extension_dict = NULL;
390 if (!i.value().GetAsDictionary(&extension_dict))
391 continue;
392 int location_value;
393 if (extension_dict->GetInteger(kPrefLocation, &location_value) &&
394 Manifest::IsUnpackedLocation(
395 static_cast<Manifest::Location>(location_value))) {
396 // Unpacked extensions can have absolute paths.
397 continue;
399 base::FilePath::StringType path_string;
400 if (!extension_dict->GetString(kPrefPath, &path_string))
401 continue;
402 base::FilePath path(path_string);
403 if (path.IsAbsolute())
404 absolute_keys.insert(i.key());
406 if (absolute_keys.empty())
407 return;
409 // Fix these paths.
410 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
411 base::DictionaryValue* update_dict = update.Get();
412 for (std::set<std::string>::iterator i = absolute_keys.begin();
413 i != absolute_keys.end(); ++i) {
414 base::DictionaryValue* extension_dict = NULL;
415 if (!update_dict->GetDictionaryWithoutPathExpansion(*i, &extension_dict)) {
416 NOTREACHED() << "Control should never reach here for extension " << *i;
417 continue;
419 base::FilePath::StringType path_string;
420 extension_dict->GetString(kPrefPath, &path_string);
421 base::FilePath path(path_string);
422 extension_dict->SetString(kPrefPath,
423 MakePathRelative(install_directory_, path));
427 const base::DictionaryValue* ExtensionPrefs::GetExtensionPref(
428 const std::string& extension_id) const {
429 const base::DictionaryValue* extensions =
430 prefs_->GetDictionary(pref_names::kExtensions);
431 const base::DictionaryValue* extension_dict = NULL;
432 if (!extensions ||
433 !extensions->GetDictionary(extension_id, &extension_dict)) {
434 return NULL;
436 return extension_dict;
439 void ExtensionPrefs::UpdateExtensionPref(const std::string& extension_id,
440 const std::string& key,
441 base::Value* data_value) {
442 if (!crx_file::id_util::IdIsValid(extension_id)) {
443 NOTREACHED() << "Invalid extension_id " << extension_id;
444 return;
446 ScopedExtensionPrefUpdate update(prefs_, extension_id);
447 if (data_value)
448 update->Set(key, data_value);
449 else
450 update->Remove(key, NULL);
453 void ExtensionPrefs::DeleteExtensionPrefs(const std::string& extension_id) {
454 extension_pref_value_map_->UnregisterExtension(extension_id);
455 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
456 observer_list_,
457 OnExtensionPrefsDeleted(extension_id));
458 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
459 base::DictionaryValue* dict = update.Get();
460 dict->Remove(extension_id, NULL);
463 bool ExtensionPrefs::ReadPrefAsBoolean(const std::string& extension_id,
464 const std::string& pref_key,
465 bool* out_value) const {
466 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
467 if (!ext || !ext->GetBoolean(pref_key, out_value))
468 return false;
470 return true;
473 bool ExtensionPrefs::ReadPrefAsInteger(const std::string& extension_id,
474 const std::string& pref_key,
475 int* out_value) const {
476 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
477 if (!ext || !ext->GetInteger(pref_key, out_value))
478 return false;
480 return true;
483 bool ExtensionPrefs::ReadPrefAsString(const std::string& extension_id,
484 const std::string& pref_key,
485 std::string* out_value) const {
486 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
487 if (!ext || !ext->GetString(pref_key, out_value))
488 return false;
490 return true;
493 bool ExtensionPrefs::ReadPrefAsList(const std::string& extension_id,
494 const std::string& pref_key,
495 const base::ListValue** out_value) const {
496 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
497 const base::ListValue* out = NULL;
498 if (!ext || !ext->GetList(pref_key, &out))
499 return false;
500 if (out_value)
501 *out_value = out;
503 return true;
506 bool ExtensionPrefs::ReadPrefAsDictionary(
507 const std::string& extension_id,
508 const std::string& pref_key,
509 const base::DictionaryValue** out_value) const {
510 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
511 const base::DictionaryValue* out = NULL;
512 if (!ext || !ext->GetDictionary(pref_key, &out))
513 return false;
514 if (out_value)
515 *out_value = out;
517 return true;
520 bool ExtensionPrefs::HasPrefForExtension(
521 const std::string& extension_id) const {
522 return GetExtensionPref(extension_id) != NULL;
525 bool ExtensionPrefs::ReadPrefAsURLPatternSet(const std::string& extension_id,
526 const std::string& pref_key,
527 URLPatternSet* result,
528 int valid_schemes) const {
529 const base::ListValue* value = NULL;
530 if (!ReadPrefAsList(extension_id, pref_key, &value))
531 return false;
532 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
533 if (!extension)
534 return false;
535 int location;
536 if (extension->GetInteger(kPrefLocation, &location) &&
537 static_cast<Manifest::Location>(location) == Manifest::COMPONENT) {
538 valid_schemes |= URLPattern::SCHEME_CHROMEUI;
541 bool allow_file_access = AllowFileAccess(extension_id);
542 return result->Populate(*value, valid_schemes, allow_file_access, NULL);
545 void ExtensionPrefs::SetExtensionPrefURLPatternSet(
546 const std::string& extension_id,
547 const std::string& pref_key,
548 const URLPatternSet& new_value) {
549 UpdateExtensionPref(extension_id, pref_key, new_value.ToValue().release());
552 bool ExtensionPrefs::ReadPrefAsBooleanAndReturn(
553 const std::string& extension_id,
554 const std::string& pref_key) const {
555 bool out_value = false;
556 return ReadPrefAsBoolean(extension_id, pref_key, &out_value) && out_value;
559 scoped_refptr<const PermissionSet> ExtensionPrefs::ReadPrefAsPermissionSet(
560 const std::string& extension_id,
561 const std::string& pref_key) const {
562 if (!GetExtensionPref(extension_id))
563 return nullptr;
565 // Retrieve the API permissions. Please refer SetExtensionPrefPermissionSet()
566 // for api_values format.
567 APIPermissionSet apis;
568 const base::ListValue* api_values = NULL;
569 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
570 if (ReadPrefAsList(extension_id, api_pref, &api_values)) {
571 APIPermissionSet::ParseFromJSON(api_values,
572 APIPermissionSet::kAllowInternalPermissions,
573 &apis, NULL, NULL);
576 // Retrieve the Manifest Keys permissions. Please refer to
577 // |SetExtensionPrefPermissionSet| for manifest_permissions_values format.
578 ManifestPermissionSet manifest_permissions;
579 const base::ListValue* manifest_permissions_values = NULL;
580 std::string manifest_permission_pref =
581 JoinPrefs(pref_key, kPrefManifestPermissions);
582 if (ReadPrefAsList(extension_id, manifest_permission_pref,
583 &manifest_permissions_values)) {
584 ManifestPermissionSet::ParseFromJSON(
585 manifest_permissions_values, &manifest_permissions, NULL, NULL);
588 // Retrieve the explicit host permissions.
589 URLPatternSet explicit_hosts;
590 ReadPrefAsURLPatternSet(
591 extension_id, JoinPrefs(pref_key, kPrefExplicitHosts),
592 &explicit_hosts, Extension::kValidHostPermissionSchemes);
594 // Retrieve the scriptable host permissions.
595 URLPatternSet scriptable_hosts;
596 ReadPrefAsURLPatternSet(
597 extension_id, JoinPrefs(pref_key, kPrefScriptableHosts),
598 &scriptable_hosts, UserScript::ValidUserScriptSchemes());
600 return make_scoped_refptr(new PermissionSet(
601 apis, manifest_permissions, explicit_hosts, scriptable_hosts));
604 // Set the API or Manifest permissions.
605 // The format of api_values is:
606 // [ "permission_name1", // permissions do not support detail.
607 // "permission_name2",
608 // {"permission_name3": value },
609 // // permission supports detail, permission detail will be stored in value.
610 // ...
611 // ]
612 template<typename T>
613 static base::ListValue* CreatePermissionList(const T& permissions) {
614 base::ListValue* values = new base::ListValue();
615 for (typename T::const_iterator i = permissions.begin();
616 i != permissions.end(); ++i) {
617 scoped_ptr<base::Value> detail(i->ToValue());
618 if (detail) {
619 base::DictionaryValue* tmp = new base::DictionaryValue();
620 tmp->Set(i->name(), detail.release());
621 values->Append(tmp);
622 } else {
623 values->Append(new base::StringValue(i->name()));
626 return values;
629 void ExtensionPrefs::SetExtensionPrefPermissionSet(
630 const std::string& extension_id,
631 const std::string& pref_key,
632 const PermissionSet* new_value) {
633 std::string api_pref = JoinPrefs(pref_key, kPrefAPIs);
634 base::ListValue* api_values = CreatePermissionList(new_value->apis());
635 UpdateExtensionPref(extension_id, api_pref, api_values);
637 std::string manifest_permissions_pref =
638 JoinPrefs(pref_key, kPrefManifestPermissions);
639 base::ListValue* manifest_permissions_values = CreatePermissionList(
640 new_value->manifest_permissions());
641 UpdateExtensionPref(extension_id,
642 manifest_permissions_pref,
643 manifest_permissions_values);
645 // Set the explicit host permissions.
646 if (!new_value->explicit_hosts().is_empty()) {
647 SetExtensionPrefURLPatternSet(extension_id,
648 JoinPrefs(pref_key, kPrefExplicitHosts),
649 new_value->explicit_hosts());
652 // Set the scriptable host permissions.
653 if (!new_value->scriptable_hosts().is_empty()) {
654 SetExtensionPrefURLPatternSet(extension_id,
655 JoinPrefs(pref_key, kPrefScriptableHosts),
656 new_value->scriptable_hosts());
660 int ExtensionPrefs::IncrementAcknowledgePromptCount(
661 const std::string& extension_id) {
662 int count = 0;
663 ReadPrefAsInteger(extension_id, kPrefAcknowledgePromptCount, &count);
664 ++count;
665 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount,
666 new base::FundamentalValue(count));
667 return count;
670 bool ExtensionPrefs::IsExternalExtensionAcknowledged(
671 const std::string& extension_id) const {
672 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalAcknowledged);
675 void ExtensionPrefs::AcknowledgeExternalExtension(
676 const std::string& extension_id) {
677 DCHECK(crx_file::id_util::IdIsValid(extension_id));
678 UpdateExtensionPref(extension_id, kPrefExternalAcknowledged,
679 new base::FundamentalValue(true));
680 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
683 bool ExtensionPrefs::IsBlacklistedExtensionAcknowledged(
684 const std::string& extension_id) const {
685 return ReadPrefAsBooleanAndReturn(extension_id, kPrefBlacklistAcknowledged);
688 void ExtensionPrefs::AcknowledgeBlacklistedExtension(
689 const std::string& extension_id) {
690 DCHECK(crx_file::id_util::IdIsValid(extension_id));
691 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged,
692 new base::FundamentalValue(true));
693 UpdateExtensionPref(extension_id, kPrefAcknowledgePromptCount, NULL);
696 bool ExtensionPrefs::IsExternalInstallFirstRun(
697 const std::string& extension_id) const {
698 return ReadPrefAsBooleanAndReturn(extension_id, kPrefExternalInstallFirstRun);
701 void ExtensionPrefs::SetExternalInstallFirstRun(
702 const std::string& extension_id) {
703 DCHECK(crx_file::id_util::IdIsValid(extension_id));
704 UpdateExtensionPref(extension_id, kPrefExternalInstallFirstRun,
705 new base::FundamentalValue(true));
708 bool ExtensionPrefs::SetAlertSystemFirstRun() {
709 if (prefs_->GetBoolean(pref_names::kAlertsInitialized)) {
710 return true;
712 prefs_->SetBoolean(pref_names::kAlertsInitialized, true);
713 return false;
716 bool ExtensionPrefs::DidExtensionEscalatePermissions(
717 const std::string& extension_id) const {
718 return HasDisableReason(extension_id,
719 Extension::DISABLE_PERMISSIONS_INCREASE) ||
720 HasDisableReason(extension_id, Extension::DISABLE_REMOTE_INSTALL);
723 int ExtensionPrefs::GetDisableReasons(const std::string& extension_id) const {
724 int value = -1;
725 if (ReadPrefAsInteger(extension_id, kPrefDisableReasons, &value) &&
726 value >= 0) {
727 return value;
729 return Extension::DISABLE_NONE;
732 bool ExtensionPrefs::HasDisableReason(
733 const std::string& extension_id,
734 Extension::DisableReason disable_reason) const {
735 return (GetDisableReasons(extension_id) & disable_reason) != 0;
738 void ExtensionPrefs::AddDisableReason(const std::string& extension_id,
739 Extension::DisableReason disable_reason) {
740 DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED));
741 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_ADD);
744 void ExtensionPrefs::AddDisableReasons(const std::string& extension_id,
745 int disable_reasons) {
746 DCHECK(!DoesExtensionHaveState(extension_id, Extension::ENABLED));
747 ModifyDisableReasons(extension_id, disable_reasons, DISABLE_REASON_ADD);
750 void ExtensionPrefs::RemoveDisableReason(
751 const std::string& extension_id,
752 Extension::DisableReason disable_reason) {
753 ModifyDisableReasons(extension_id, disable_reason, DISABLE_REASON_REMOVE);
756 void ExtensionPrefs::ClearDisableReasons(const std::string& extension_id) {
757 ModifyDisableReasons(extension_id, Extension::DISABLE_NONE,
758 DISABLE_REASON_CLEAR);
761 void ExtensionPrefs::ModifyDisableReasons(const std::string& extension_id,
762 int reasons,
763 DisableReasonChange change) {
764 int old_value = GetDisableReasons(extension_id);
765 int new_value = old_value;
766 switch (change) {
767 case DISABLE_REASON_ADD:
768 new_value |= reasons;
769 break;
770 case DISABLE_REASON_REMOVE:
771 new_value &= ~reasons;
772 break;
773 case DISABLE_REASON_CLEAR:
774 new_value = Extension::DISABLE_NONE;
775 break;
778 if (old_value == new_value) // no change, return.
779 return;
781 if (new_value == Extension::DISABLE_NONE) {
782 UpdateExtensionPref(extension_id, kPrefDisableReasons, NULL);
783 } else {
784 UpdateExtensionPref(extension_id,
785 kPrefDisableReasons,
786 new base::FundamentalValue(new_value));
789 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
790 observer_list_,
791 OnExtensionDisableReasonsChanged(extension_id, new_value));
794 std::set<std::string> ExtensionPrefs::GetBlacklistedExtensions() const {
795 std::set<std::string> ids;
797 const base::DictionaryValue* extensions =
798 prefs_->GetDictionary(pref_names::kExtensions);
799 if (!extensions)
800 return ids;
802 for (base::DictionaryValue::Iterator it(*extensions);
803 !it.IsAtEnd(); it.Advance()) {
804 if (!it.value().IsType(base::Value::TYPE_DICTIONARY)) {
805 NOTREACHED() << "Invalid pref for extension " << it.key();
806 continue;
808 if (IsBlacklistBitSet(
809 static_cast<const base::DictionaryValue*>(&it.value()))) {
810 ids.insert(it.key());
814 return ids;
817 void ExtensionPrefs::SetExtensionBlacklisted(const std::string& extension_id,
818 bool is_blacklisted) {
819 bool currently_blacklisted = IsExtensionBlacklisted(extension_id);
820 if (is_blacklisted == currently_blacklisted)
821 return;
823 // Always make sure the "acknowledged" bit is cleared since the blacklist bit
824 // is changing.
825 UpdateExtensionPref(extension_id, kPrefBlacklistAcknowledged, NULL);
827 if (is_blacklisted) {
828 UpdateExtensionPref(extension_id,
829 kPrefBlacklist,
830 new base::FundamentalValue(true));
831 } else {
832 UpdateExtensionPref(extension_id, kPrefBlacklist, NULL);
833 const base::DictionaryValue* dict = GetExtensionPref(extension_id);
834 if (dict && dict->empty())
835 DeleteExtensionPrefs(extension_id);
839 bool ExtensionPrefs::IsExtensionBlacklisted(const std::string& id) const {
840 const base::DictionaryValue* ext_prefs = GetExtensionPref(id);
841 return ext_prefs && IsBlacklistBitSet(ext_prefs);
844 namespace {
846 // Serializes a 64bit integer as a string value.
847 void SaveInt64(base::DictionaryValue* dictionary,
848 const char* key,
849 const int64 value) {
850 if (!dictionary)
851 return;
853 std::string string_value = base::Int64ToString(value);
854 dictionary->SetString(key, string_value);
857 // Deserializes a 64bit integer stored as a string value.
858 bool ReadInt64(const base::DictionaryValue* dictionary,
859 const char* key,
860 int64* value) {
861 if (!dictionary)
862 return false;
864 std::string string_value;
865 if (!dictionary->GetString(key, &string_value))
866 return false;
868 return base::StringToInt64(string_value, value);
871 // Serializes |time| as a string value mapped to |key| in |dictionary|.
872 void SaveTime(base::DictionaryValue* dictionary,
873 const char* key,
874 const base::Time& time) {
875 SaveInt64(dictionary, key, time.ToInternalValue());
878 // The opposite of SaveTime. If |key| is not found, this returns an empty Time
879 // (is_null() will return true).
880 base::Time ReadTime(const base::DictionaryValue* dictionary, const char* key) {
881 int64 value;
882 if (ReadInt64(dictionary, key, &value))
883 return base::Time::FromInternalValue(value);
885 return base::Time();
888 } // namespace
890 base::Time ExtensionPrefs::LastPingDay(const std::string& extension_id) const {
891 DCHECK(crx_file::id_util::IdIsValid(extension_id));
892 return ReadTime(GetExtensionPref(extension_id), kLastPingDay);
895 void ExtensionPrefs::SetLastPingDay(const std::string& extension_id,
896 const base::Time& time) {
897 DCHECK(crx_file::id_util::IdIsValid(extension_id));
898 ScopedExtensionPrefUpdate update(prefs_, extension_id);
899 SaveTime(update.Get(), kLastPingDay, time);
902 base::Time ExtensionPrefs::BlacklistLastPingDay() const {
903 return ReadTime(prefs_->GetDictionary(kExtensionsBlacklistUpdate),
904 kLastPingDay);
907 void ExtensionPrefs::SetBlacklistLastPingDay(const base::Time& time) {
908 DictionaryPrefUpdate update(prefs_, kExtensionsBlacklistUpdate);
909 SaveTime(update.Get(), kLastPingDay, time);
912 base::Time ExtensionPrefs::LastActivePingDay(
913 const std::string& extension_id) const {
914 DCHECK(crx_file::id_util::IdIsValid(extension_id));
915 return ReadTime(GetExtensionPref(extension_id), kLastActivePingDay);
918 void ExtensionPrefs::SetLastActivePingDay(const std::string& extension_id,
919 const base::Time& time) {
920 DCHECK(crx_file::id_util::IdIsValid(extension_id));
921 ScopedExtensionPrefUpdate update(prefs_, extension_id);
922 SaveTime(update.Get(), kLastActivePingDay, time);
925 bool ExtensionPrefs::GetActiveBit(const std::string& extension_id) const {
926 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
927 bool result = false;
928 if (dictionary && dictionary->GetBoolean(kActiveBit, &result))
929 return result;
930 return false;
933 void ExtensionPrefs::SetActiveBit(const std::string& extension_id,
934 bool active) {
935 UpdateExtensionPref(extension_id, kActiveBit,
936 new base::FundamentalValue(active));
939 void ExtensionPrefs::MigratePermissions(const ExtensionIdList& extension_ids) {
940 PermissionsInfo* info = PermissionsInfo::GetInstance();
941 for (ExtensionIdList::const_iterator ext_id =
942 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
943 // An extension's granted permissions need to be migrated if the
944 // full_access bit is present. This bit was always present in the previous
945 // scheme and is never present now.
946 bool full_access = false;
947 const base::DictionaryValue* ext = GetExtensionPref(*ext_id);
948 if (!ext || !ext->GetBoolean(kPrefOldGrantedFullAccess, &full_access))
949 continue;
951 // Remove the full access bit (empty list will get trimmed).
952 UpdateExtensionPref(
953 *ext_id, kPrefOldGrantedFullAccess, new base::ListValue());
955 // Add the plugin permission if the full access bit was set.
956 if (full_access) {
957 const base::ListValue* apis = NULL;
958 base::ListValue* new_apis = NULL;
960 std::string granted_apis = JoinPrefs(kPrefGrantedPermissions, kPrefAPIs);
961 if (ext->GetList(kPrefOldGrantedAPIs, &apis))
962 new_apis = apis->DeepCopy();
963 else
964 new_apis = new base::ListValue();
966 std::string plugin_name = info->GetByID(APIPermission::kPlugin)->name();
967 new_apis->Append(new base::StringValue(plugin_name));
968 UpdateExtensionPref(*ext_id, granted_apis, new_apis);
971 // The granted permissions originally only held the effective hosts,
972 // which are a combination of host and user script host permissions.
973 // We now maintain these lists separately. For migration purposes, it
974 // does not matter how we treat the old effective hosts as long as the
975 // new effective hosts will be the same, so we move them to explicit
976 // host permissions.
977 const base::ListValue* hosts = NULL;
978 std::string explicit_hosts =
979 JoinPrefs(kPrefGrantedPermissions, kPrefExplicitHosts);
980 if (ext->GetList(kPrefOldGrantedHosts, &hosts)) {
981 UpdateExtensionPref(
982 *ext_id, explicit_hosts, hosts->DeepCopy());
984 // We can get rid of the old one by setting it to an empty list.
985 UpdateExtensionPref(*ext_id, kPrefOldGrantedHosts, new base::ListValue());
990 void ExtensionPrefs::MigrateDisableReasons(
991 const ExtensionIdList& extension_ids) {
992 for (ExtensionIdList::const_iterator ext_id =
993 extension_ids.begin(); ext_id != extension_ids.end(); ++ext_id) {
994 int value = -1;
995 if (ReadPrefAsInteger(*ext_id, kDeprecatedPrefDisableReason, &value)) {
996 int new_value = Extension::DISABLE_NONE;
997 switch (value) {
998 case Extension::DEPRECATED_DISABLE_USER_ACTION:
999 new_value = Extension::DISABLE_USER_ACTION;
1000 break;
1001 case Extension::DEPRECATED_DISABLE_PERMISSIONS_INCREASE:
1002 new_value = Extension::DISABLE_PERMISSIONS_INCREASE;
1003 break;
1004 case Extension::DEPRECATED_DISABLE_RELOAD:
1005 new_value = Extension::DISABLE_RELOAD;
1006 break;
1009 UpdateExtensionPref(*ext_id, kPrefDisableReasons,
1010 new base::FundamentalValue(new_value));
1011 // Remove the old disable reason.
1012 UpdateExtensionPref(*ext_id, kDeprecatedPrefDisableReason, NULL);
1017 scoped_refptr<const PermissionSet> ExtensionPrefs::GetGrantedPermissions(
1018 const std::string& extension_id) const {
1019 CHECK(crx_file::id_util::IdIsValid(extension_id));
1020 return ReadPrefAsPermissionSet(extension_id, kPrefGrantedPermissions);
1023 void ExtensionPrefs::AddGrantedPermissions(
1024 const std::string& extension_id,
1025 const PermissionSet* permissions) {
1026 CHECK(crx_file::id_util::IdIsValid(extension_id));
1027 DCHECK(permissions);
1029 scoped_refptr<const PermissionSet> granted =
1030 GetGrantedPermissions(extension_id);
1031 granted = granted.get() ? PermissionSet::CreateUnion(*permissions, *granted)
1032 : permissions;
1033 // The new granted permissions are the union of the already granted
1034 // permissions and the newly granted permissions.
1035 SetExtensionPrefPermissionSet(extension_id, kPrefGrantedPermissions,
1036 granted.get());
1039 void ExtensionPrefs::RemoveGrantedPermissions(
1040 const std::string& extension_id,
1041 const PermissionSet* permissions) {
1042 CHECK(crx_file::id_util::IdIsValid(extension_id));
1044 // The new granted permissions are the difference of the already granted
1045 // permissions and the newly ungranted permissions.
1046 SetExtensionPrefPermissionSet(
1047 extension_id, kPrefGrantedPermissions,
1048 PermissionSet::CreateDifference(*GetGrantedPermissions(extension_id),
1049 *permissions)
1050 .get());
1053 scoped_refptr<const PermissionSet> ExtensionPrefs::GetActivePermissions(
1054 const std::string& extension_id) const {
1055 CHECK(crx_file::id_util::IdIsValid(extension_id));
1056 return ReadPrefAsPermissionSet(extension_id, kPrefActivePermissions);
1059 void ExtensionPrefs::SetActivePermissions(
1060 const std::string& extension_id,
1061 const PermissionSet* permissions) {
1062 SetExtensionPrefPermissionSet(
1063 extension_id, kPrefActivePermissions, permissions);
1066 void ExtensionPrefs::SetExtensionRunning(const std::string& extension_id,
1067 bool is_running) {
1068 base::Value* value = new base::FundamentalValue(is_running);
1069 UpdateExtensionPref(extension_id, kPrefRunning, value);
1072 bool ExtensionPrefs::IsExtensionRunning(const std::string& extension_id) const {
1073 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1074 if (!extension)
1075 return false;
1076 bool running = false;
1077 extension->GetBoolean(kPrefRunning, &running);
1078 return running;
1081 void ExtensionPrefs::SetIsActive(const std::string& extension_id,
1082 bool is_active) {
1083 base::Value* value = new base::FundamentalValue(is_active);
1084 UpdateExtensionPref(extension_id, kIsActive, value);
1087 bool ExtensionPrefs::IsActive(const std::string& extension_id) const {
1088 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1089 if (!extension)
1090 return false;
1091 bool is_active = false;
1092 extension->GetBoolean(kIsActive, &is_active);
1093 return is_active;
1096 bool ExtensionPrefs::IsIncognitoEnabled(const std::string& extension_id) const {
1097 return ReadPrefAsBooleanAndReturn(extension_id, kPrefIncognitoEnabled);
1100 void ExtensionPrefs::SetIsIncognitoEnabled(const std::string& extension_id,
1101 bool enabled) {
1102 UpdateExtensionPref(extension_id, kPrefIncognitoEnabled,
1103 new base::FundamentalValue(enabled));
1104 extension_pref_value_map_->SetExtensionIncognitoState(extension_id, enabled);
1107 bool ExtensionPrefs::AllowFileAccess(const std::string& extension_id) const {
1108 return ReadPrefAsBooleanAndReturn(extension_id, kPrefAllowFileAccess);
1111 void ExtensionPrefs::SetAllowFileAccess(const std::string& extension_id,
1112 bool allow) {
1113 UpdateExtensionPref(extension_id, kPrefAllowFileAccess,
1114 new base::FundamentalValue(allow));
1117 bool ExtensionPrefs::HasAllowFileAccessSetting(
1118 const std::string& extension_id) const {
1119 const base::DictionaryValue* ext = GetExtensionPref(extension_id);
1120 return ext && ext->HasKey(kPrefAllowFileAccess);
1123 bool ExtensionPrefs::DoesExtensionHaveState(
1124 const std::string& id, Extension::State check_state) const {
1125 const base::DictionaryValue* extension = GetExtensionPref(id);
1126 int state = -1;
1127 if (!extension || !extension->GetInteger(kPrefState, &state))
1128 return false;
1130 if (state < 0 || state >= Extension::NUM_STATES) {
1131 LOG(ERROR) << "Bad pref 'state' for extension '" << id << "'";
1132 return false;
1135 return state == check_state;
1138 bool ExtensionPrefs::IsExternalExtensionUninstalled(
1139 const std::string& id) const {
1140 return DoesExtensionHaveState(id, Extension::EXTERNAL_EXTENSION_UNINSTALLED);
1143 bool ExtensionPrefs::IsExtensionDisabled(const std::string& id) const {
1144 return DoesExtensionHaveState(id, Extension::DISABLED);
1147 ExtensionIdList ExtensionPrefs::GetToolbarOrder() const {
1148 ExtensionIdList id_list_out;
1149 GetUserExtensionPrefIntoContainer(pref_names::kToolbar, &id_list_out);
1150 return id_list_out;
1153 void ExtensionPrefs::SetToolbarOrder(const ExtensionIdList& extension_ids) {
1154 SetExtensionPrefFromContainer(pref_names::kToolbar, extension_ids);
1157 void ExtensionPrefs::OnExtensionInstalled(
1158 const Extension* extension,
1159 Extension::State initial_state,
1160 const syncer::StringOrdinal& page_ordinal,
1161 int install_flags,
1162 const std::string& install_parameter) {
1163 ScopedExtensionPrefUpdate update(prefs_, extension->id());
1164 base::DictionaryValue* extension_dict = update.Get();
1165 const base::Time install_time = time_provider_->GetCurrentTime();
1166 PopulateExtensionInfoPrefs(extension,
1167 install_time,
1168 initial_state,
1169 install_flags,
1170 install_parameter,
1171 extension_dict);
1173 bool requires_sort_ordinal = extension->RequiresSortOrdinal() &&
1174 (install_flags & kInstallFlagIsEphemeral) == 0;
1175 FinishExtensionInfoPrefs(extension->id(),
1176 install_time,
1177 requires_sort_ordinal,
1178 page_ordinal,
1179 extension_dict);
1182 void ExtensionPrefs::OnExtensionUninstalled(const std::string& extension_id,
1183 const Manifest::Location& location,
1184 bool external_uninstall) {
1185 app_sorting()->ClearOrdinals(extension_id);
1187 // For external extensions, we save a preference reminding ourself not to try
1188 // and install the extension anymore (except when |external_uninstall| is
1189 // true, which signifies that the registry key was deleted or the pref file
1190 // no longer lists the extension).
1191 if (!external_uninstall && Manifest::IsExternalLocation(location)) {
1192 UpdateExtensionPref(extension_id, kPrefState,
1193 new base::FundamentalValue(
1194 Extension::EXTERNAL_EXTENSION_UNINSTALLED));
1195 extension_pref_value_map_->SetExtensionState(extension_id, false);
1196 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
1197 observer_list_,
1198 OnExtensionStateChanged(extension_id, false));
1199 } else {
1200 DeleteExtensionPrefs(extension_id);
1204 void ExtensionPrefs::SetExtensionEnabled(const std::string& extension_id) {
1205 UpdateExtensionPref(extension_id, kPrefState,
1206 new base::FundamentalValue(Extension::ENABLED));
1207 extension_pref_value_map_->SetExtensionState(extension_id, true);
1208 UpdateExtensionPref(extension_id, kPrefDisableReasons, nullptr);
1209 FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_,
1210 OnExtensionStateChanged(extension_id, true));
1213 void ExtensionPrefs::SetExtensionDisabled(const std::string& extension_id,
1214 int disable_reasons) {
1215 if (!IsExternalExtensionUninstalled(extension_id)) {
1216 UpdateExtensionPref(extension_id, kPrefState,
1217 new base::FundamentalValue(Extension::DISABLED));
1218 extension_pref_value_map_->SetExtensionState(extension_id, false);
1220 UpdateExtensionPref(extension_id, kPrefDisableReasons,
1221 new base::FundamentalValue(disable_reasons));
1222 FOR_EACH_OBSERVER(ExtensionPrefsObserver, observer_list_,
1223 OnExtensionStateChanged(extension_id, false));
1226 void ExtensionPrefs::SetExtensionBlacklistState(const std::string& extension_id,
1227 BlacklistState state) {
1228 SetExtensionBlacklisted(extension_id, state == BLACKLISTED_MALWARE);
1229 UpdateExtensionPref(extension_id, kPrefBlacklistState,
1230 new base::FundamentalValue(state));
1233 BlacklistState ExtensionPrefs::GetExtensionBlacklistState(
1234 const std::string& extension_id) const {
1235 if (IsExtensionBlacklisted(extension_id))
1236 return BLACKLISTED_MALWARE;
1237 const base::DictionaryValue* ext_prefs = GetExtensionPref(extension_id);
1238 int int_value = 0;
1239 if (ext_prefs && ext_prefs->GetInteger(kPrefBlacklistState, &int_value))
1240 return static_cast<BlacklistState>(int_value);
1242 return NOT_BLACKLISTED;
1245 std::string ExtensionPrefs::GetVersionString(
1246 const std::string& extension_id) const {
1247 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1248 if (!extension)
1249 return std::string();
1251 std::string version;
1252 extension->GetString(kPrefVersion, &version);
1254 return version;
1257 void ExtensionPrefs::UpdateManifest(const Extension* extension) {
1258 if (!Manifest::IsUnpackedLocation(extension->location())) {
1259 const base::DictionaryValue* extension_dict =
1260 GetExtensionPref(extension->id());
1261 if (!extension_dict)
1262 return;
1263 const base::DictionaryValue* old_manifest = NULL;
1264 bool update_required =
1265 !extension_dict->GetDictionary(kPrefManifest, &old_manifest) ||
1266 !extension->manifest()->value()->Equals(old_manifest);
1267 if (update_required) {
1268 UpdateExtensionPref(extension->id(), kPrefManifest,
1269 extension->manifest()->value()->DeepCopy());
1274 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledInfoHelper(
1275 const std::string& extension_id,
1276 const base::DictionaryValue* extension) const {
1277 int location_value;
1278 if (!extension->GetInteger(kPrefLocation, &location_value))
1279 return scoped_ptr<ExtensionInfo>();
1281 Manifest::Location location = static_cast<Manifest::Location>(location_value);
1282 if (location == Manifest::COMPONENT) {
1283 // Component extensions are ignored. Component extensions may have data
1284 // saved in preferences, but they are already loaded at this point (by
1285 // ComponentLoader) and shouldn't be populated into the result of
1286 // GetInstalledExtensionsInfo, otherwise InstalledLoader would also want to
1287 // load them.
1288 return scoped_ptr<ExtensionInfo>();
1291 // Only the following extension types have data saved in the preferences.
1292 if (location != Manifest::INTERNAL &&
1293 !Manifest::IsUnpackedLocation(location) &&
1294 !Manifest::IsExternalLocation(location)) {
1295 NOTREACHED();
1296 return scoped_ptr<ExtensionInfo>();
1299 const base::DictionaryValue* manifest = NULL;
1300 if (!Manifest::IsUnpackedLocation(location) &&
1301 !extension->GetDictionary(kPrefManifest, &manifest)) {
1302 LOG(WARNING) << "Missing manifest for extension " << extension_id;
1303 // Just a warning for now.
1306 base::FilePath::StringType path;
1307 if (!extension->GetString(kPrefPath, &path))
1308 return scoped_ptr<ExtensionInfo>();
1310 // Make path absolute. Most (but not all) extension types have relative paths.
1311 if (!base::FilePath(path).IsAbsolute())
1312 path = install_directory_.Append(path).value();
1314 return scoped_ptr<ExtensionInfo>(new ExtensionInfo(
1315 manifest, extension_id, base::FilePath(path), location));
1318 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetInstalledExtensionInfo(
1319 const std::string& extension_id) const {
1320 const base::DictionaryValue* ext = NULL;
1321 const base::DictionaryValue* extensions =
1322 prefs_->GetDictionary(pref_names::kExtensions);
1323 if (!extensions ||
1324 !extensions->GetDictionaryWithoutPathExpansion(extension_id, &ext))
1325 return scoped_ptr<ExtensionInfo>();
1326 int state_value;
1327 if (ext->GetInteger(kPrefState, &state_value) &&
1328 state_value == Extension::EXTERNAL_EXTENSION_UNINSTALLED) {
1329 LOG(WARNING) << "External extension with id " << extension_id
1330 << " has been uninstalled by the user";
1331 return scoped_ptr<ExtensionInfo>();
1334 return GetInstalledInfoHelper(extension_id, ext);
1337 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1338 ExtensionPrefs::GetInstalledExtensionsInfo() const {
1339 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1341 const base::DictionaryValue* extensions =
1342 prefs_->GetDictionary(pref_names::kExtensions);
1343 for (base::DictionaryValue::Iterator extension_id(*extensions);
1344 !extension_id.IsAtEnd(); extension_id.Advance()) {
1345 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1346 continue;
1348 scoped_ptr<ExtensionInfo> info =
1349 GetInstalledExtensionInfo(extension_id.key());
1350 if (info)
1351 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1354 return extensions_info.Pass();
1357 scoped_ptr<ExtensionPrefs::ExtensionsInfo>
1358 ExtensionPrefs::GetUninstalledExtensionsInfo() const {
1359 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1361 const base::DictionaryValue* extensions =
1362 prefs_->GetDictionary(pref_names::kExtensions);
1363 for (base::DictionaryValue::Iterator extension_id(*extensions);
1364 !extension_id.IsAtEnd(); extension_id.Advance()) {
1365 const base::DictionaryValue* ext = NULL;
1366 if (!crx_file::id_util::IdIsValid(extension_id.key()) ||
1367 !IsExternalExtensionUninstalled(extension_id.key()) ||
1368 !extension_id.value().GetAsDictionary(&ext))
1369 continue;
1371 scoped_ptr<ExtensionInfo> info =
1372 GetInstalledInfoHelper(extension_id.key(), ext);
1373 if (info)
1374 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1377 return extensions_info.Pass();
1380 void ExtensionPrefs::SetDelayedInstallInfo(
1381 const Extension* extension,
1382 Extension::State initial_state,
1383 int install_flags,
1384 DelayReason delay_reason,
1385 const syncer::StringOrdinal& page_ordinal,
1386 const std::string& install_parameter) {
1387 base::DictionaryValue* extension_dict = new base::DictionaryValue();
1388 PopulateExtensionInfoPrefs(extension,
1389 time_provider_->GetCurrentTime(),
1390 initial_state,
1391 install_flags,
1392 install_parameter,
1393 extension_dict);
1395 // Add transient data that is needed by FinishDelayedInstallInfo(), but
1396 // should not be in the final extension prefs. All entries here should have
1397 // a corresponding Remove() call in FinishDelayedInstallInfo().
1398 if (extension->RequiresSortOrdinal() &&
1399 (install_flags & kInstallFlagIsEphemeral) == 0) {
1400 extension_dict->SetString(
1401 kPrefSuggestedPageOrdinal,
1402 page_ordinal.IsValid() ? page_ordinal.ToInternalValue()
1403 : std::string());
1405 extension_dict->SetInteger(kDelayedInstallReason,
1406 static_cast<int>(delay_reason));
1408 UpdateExtensionPref(extension->id(), kDelayedInstallInfo, extension_dict);
1411 bool ExtensionPrefs::RemoveDelayedInstallInfo(
1412 const std::string& extension_id) {
1413 if (!GetExtensionPref(extension_id))
1414 return false;
1415 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1416 bool result = update->Remove(kDelayedInstallInfo, NULL);
1417 return result;
1420 bool ExtensionPrefs::FinishDelayedInstallInfo(
1421 const std::string& extension_id) {
1422 CHECK(crx_file::id_util::IdIsValid(extension_id));
1423 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1424 base::DictionaryValue* extension_dict = update.Get();
1425 base::DictionaryValue* pending_install_dict = NULL;
1426 if (!extension_dict->GetDictionary(kDelayedInstallInfo,
1427 &pending_install_dict)) {
1428 return false;
1431 // Retrieve and clear transient values populated by SetDelayedInstallInfo().
1432 // Also do any other data cleanup that makes sense.
1433 std::string serialized_ordinal;
1434 syncer::StringOrdinal suggested_page_ordinal;
1435 bool needs_sort_ordinal = false;
1436 if (pending_install_dict->GetString(kPrefSuggestedPageOrdinal,
1437 &serialized_ordinal)) {
1438 suggested_page_ordinal = syncer::StringOrdinal(serialized_ordinal);
1439 needs_sort_ordinal = true;
1440 pending_install_dict->Remove(kPrefSuggestedPageOrdinal, NULL);
1442 pending_install_dict->Remove(kDelayedInstallReason, NULL);
1444 const base::Time install_time = time_provider_->GetCurrentTime();
1445 pending_install_dict->Set(
1446 kPrefInstallTime,
1447 new base::StringValue(
1448 base::Int64ToString(install_time.ToInternalValue())));
1450 // Some extension pref values are written conditionally. If they are not
1451 // present in the delayed install data, they should be removed when the
1452 // delayed install is committed.
1453 extension_dict->Remove(kPrefEphemeralApp, NULL);
1455 // Commit the delayed install data.
1456 for (base::DictionaryValue::Iterator it(*pending_install_dict); !it.IsAtEnd();
1457 it.Advance()) {
1458 extension_dict->Set(it.key(), it.value().DeepCopy());
1460 FinishExtensionInfoPrefs(extension_id, install_time, needs_sort_ordinal,
1461 suggested_page_ordinal, extension_dict);
1462 return true;
1465 scoped_ptr<ExtensionInfo> ExtensionPrefs::GetDelayedInstallInfo(
1466 const std::string& extension_id) const {
1467 const base::DictionaryValue* extension_prefs =
1468 GetExtensionPref(extension_id);
1469 if (!extension_prefs)
1470 return scoped_ptr<ExtensionInfo>();
1472 const base::DictionaryValue* ext = NULL;
1473 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1474 return scoped_ptr<ExtensionInfo>();
1476 return GetInstalledInfoHelper(extension_id, ext);
1479 ExtensionPrefs::DelayReason ExtensionPrefs::GetDelayedInstallReason(
1480 const std::string& extension_id) const {
1481 const base::DictionaryValue* extension_prefs =
1482 GetExtensionPref(extension_id);
1483 if (!extension_prefs)
1484 return DELAY_REASON_NONE;
1486 const base::DictionaryValue* ext = NULL;
1487 if (!extension_prefs->GetDictionary(kDelayedInstallInfo, &ext))
1488 return DELAY_REASON_NONE;
1490 int delay_reason;
1491 if (!ext->GetInteger(kDelayedInstallReason, &delay_reason))
1492 return DELAY_REASON_NONE;
1494 return static_cast<DelayReason>(delay_reason);
1497 scoped_ptr<ExtensionPrefs::ExtensionsInfo> ExtensionPrefs::
1498 GetAllDelayedInstallInfo() const {
1499 scoped_ptr<ExtensionsInfo> extensions_info(new ExtensionsInfo);
1501 const base::DictionaryValue* extensions =
1502 prefs_->GetDictionary(pref_names::kExtensions);
1503 for (base::DictionaryValue::Iterator extension_id(*extensions);
1504 !extension_id.IsAtEnd(); extension_id.Advance()) {
1505 if (!crx_file::id_util::IdIsValid(extension_id.key()))
1506 continue;
1508 scoped_ptr<ExtensionInfo> info = GetDelayedInstallInfo(extension_id.key());
1509 if (info)
1510 extensions_info->push_back(linked_ptr<ExtensionInfo>(info.release()));
1513 return extensions_info.Pass();
1516 bool ExtensionPrefs::IsEphemeralApp(const std::string& extension_id) const {
1517 if (ReadPrefAsBooleanAndReturn(extension_id, kPrefEphemeralApp))
1518 return true;
1520 // Ephemerality was previously stored in the creation flags, so we must also
1521 // check it for backcompatibility.
1522 return (GetCreationFlags(extension_id) & Extension::IS_EPHEMERAL) != 0;
1525 void ExtensionPrefs::OnEphemeralAppPromoted(const std::string& extension_id) {
1526 DCHECK(IsEphemeralApp(extension_id));
1528 UpdateExtensionPref(extension_id, kPrefEphemeralApp, NULL);
1530 // Ephemerality was previously stored in the creation flags, so ensure the bit
1531 // is cleared.
1532 int creation_flags = Extension::NO_FLAGS;
1533 if (ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1534 if (creation_flags & Extension::IS_EPHEMERAL) {
1535 creation_flags &= ~static_cast<int>(Extension::IS_EPHEMERAL);
1536 UpdateExtensionPref(extension_id,
1537 kPrefCreationFlags,
1538 new base::FundamentalValue(creation_flags));
1543 bool ExtensionPrefs::WasAppDraggedByUser(
1544 const std::string& extension_id) const {
1545 return ReadPrefAsBooleanAndReturn(extension_id, kPrefUserDraggedApp);
1548 void ExtensionPrefs::SetAppDraggedByUser(const std::string& extension_id) {
1549 UpdateExtensionPref(extension_id, kPrefUserDraggedApp,
1550 new base::FundamentalValue(true));
1553 bool ExtensionPrefs::IsFromWebStore(
1554 const std::string& extension_id) const {
1555 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1556 bool result = false;
1557 if (dictionary && dictionary->GetBoolean(kPrefFromWebStore, &result))
1558 return result;
1559 return false;
1562 bool ExtensionPrefs::IsFromBookmark(
1563 const std::string& extension_id) const {
1564 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1565 bool result = false;
1566 if (dictionary && dictionary->GetBoolean(kPrefFromBookmark, &result))
1567 return result;
1568 return false;
1571 int ExtensionPrefs::GetCreationFlags(const std::string& extension_id) const {
1572 int creation_flags = Extension::NO_FLAGS;
1573 if (!ReadPrefAsInteger(extension_id, kPrefCreationFlags, &creation_flags)) {
1574 // Since kPrefCreationFlags was added later, it will be missing for
1575 // previously installed extensions.
1576 if (IsFromBookmark(extension_id))
1577 creation_flags |= Extension::FROM_BOOKMARK;
1578 if (IsFromWebStore(extension_id))
1579 creation_flags |= Extension::FROM_WEBSTORE;
1580 if (WasInstalledByDefault(extension_id))
1581 creation_flags |= Extension::WAS_INSTALLED_BY_DEFAULT;
1582 if (WasInstalledByOem(extension_id))
1583 creation_flags |= Extension::WAS_INSTALLED_BY_OEM;
1585 return creation_flags;
1588 int ExtensionPrefs::GetDelayedInstallCreationFlags(
1589 const std::string& extension_id) const {
1590 int creation_flags = Extension::NO_FLAGS;
1591 const base::DictionaryValue* delayed_info = NULL;
1592 if (ReadPrefAsDictionary(extension_id, kDelayedInstallInfo, &delayed_info)) {
1593 delayed_info->GetInteger(kPrefCreationFlags, &creation_flags);
1595 return creation_flags;
1598 bool ExtensionPrefs::WasInstalledByDefault(
1599 const std::string& extension_id) const {
1600 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1601 bool result = false;
1602 if (dictionary &&
1603 dictionary->GetBoolean(kPrefWasInstalledByDefault, &result))
1604 return result;
1605 return false;
1608 bool ExtensionPrefs::WasInstalledByOem(const std::string& extension_id) const {
1609 const base::DictionaryValue* dictionary = GetExtensionPref(extension_id);
1610 bool result = false;
1611 if (dictionary && dictionary->GetBoolean(kPrefWasInstalledByOem, &result))
1612 return result;
1613 return false;
1616 base::Time ExtensionPrefs::GetInstallTime(
1617 const std::string& extension_id) const {
1618 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1619 if (!extension) {
1620 NOTREACHED();
1621 return base::Time();
1623 std::string install_time_str;
1624 if (!extension->GetString(kPrefInstallTime, &install_time_str))
1625 return base::Time();
1626 int64 install_time_i64 = 0;
1627 if (!base::StringToInt64(install_time_str, &install_time_i64))
1628 return base::Time();
1629 return base::Time::FromInternalValue(install_time_i64);
1632 bool ExtensionPrefs::DoNotSync(const std::string& extension_id) const {
1633 bool do_not_sync;
1634 if (!ReadPrefAsBoolean(extension_id, kPrefDoNotSync, &do_not_sync))
1635 return false;
1637 return do_not_sync;
1640 base::Time ExtensionPrefs::GetLastLaunchTime(
1641 const std::string& extension_id) const {
1642 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1643 if (!extension)
1644 return base::Time();
1646 std::string launch_time_str;
1647 if (!extension->GetString(kPrefLastLaunchTime, &launch_time_str))
1648 return base::Time();
1649 int64 launch_time_i64 = 0;
1650 if (!base::StringToInt64(launch_time_str, &launch_time_i64))
1651 return base::Time();
1652 return base::Time::FromInternalValue(launch_time_i64);
1655 void ExtensionPrefs::SetLastLaunchTime(const std::string& extension_id,
1656 const base::Time& time) {
1657 DCHECK(crx_file::id_util::IdIsValid(extension_id));
1658 ScopedExtensionPrefUpdate update(prefs_, extension_id);
1659 SaveTime(update.Get(), kPrefLastLaunchTime, time);
1662 void ExtensionPrefs::ClearLastLaunchTimes() {
1663 const base::DictionaryValue* dict =
1664 prefs_->GetDictionary(pref_names::kExtensions);
1665 if (!dict || dict->empty())
1666 return;
1668 // Collect all the keys to remove the last launched preference from.
1669 DictionaryPrefUpdate update(prefs_, pref_names::kExtensions);
1670 base::DictionaryValue* update_dict = update.Get();
1671 for (base::DictionaryValue::Iterator i(*update_dict); !i.IsAtEnd();
1672 i.Advance()) {
1673 base::DictionaryValue* extension_dict = NULL;
1674 if (!update_dict->GetDictionary(i.key(), &extension_dict))
1675 continue;
1677 if (extension_dict->HasKey(kPrefLastLaunchTime))
1678 extension_dict->Remove(kPrefLastLaunchTime, NULL);
1682 void ExtensionPrefs::GetExtensions(ExtensionIdList* out) const {
1683 CHECK(out);
1685 scoped_ptr<ExtensionsInfo> extensions_info(GetInstalledExtensionsInfo());
1687 for (size_t i = 0; i < extensions_info->size(); ++i) {
1688 ExtensionInfo* info = extensions_info->at(i).get();
1689 out->push_back(info->extension_id);
1693 // static
1694 ExtensionIdList ExtensionPrefs::GetExtensionsFrom(
1695 const PrefService* pref_service) {
1696 ExtensionIdList result;
1698 const base::DictionaryValue* extension_prefs = NULL;
1699 const base::Value* extension_prefs_value =
1700 pref_service->GetUserPrefValue(pref_names::kExtensions);
1701 if (!extension_prefs_value ||
1702 !extension_prefs_value->GetAsDictionary(&extension_prefs)) {
1703 return result; // Empty set
1706 for (base::DictionaryValue::Iterator it(*extension_prefs); !it.IsAtEnd();
1707 it.Advance()) {
1708 const base::DictionaryValue* ext = NULL;
1709 if (!it.value().GetAsDictionary(&ext)) {
1710 NOTREACHED() << "Invalid pref for extension " << it.key();
1711 continue;
1713 if (!IsBlacklistBitSet(ext))
1714 result.push_back(it.key());
1716 return result;
1719 void ExtensionPrefs::AddObserver(ExtensionPrefsObserver* observer) {
1720 observer_list_.AddObserver(observer);
1723 void ExtensionPrefs::RemoveObserver(ExtensionPrefsObserver* observer) {
1724 observer_list_.RemoveObserver(observer);
1727 void ExtensionPrefs::FixMissingPrefs(const ExtensionIdList& extension_ids) {
1728 // Fix old entries that did not get an installation time entry when they
1729 // were installed or don't have a preferences field.
1730 for (ExtensionIdList::const_iterator ext_id = extension_ids.begin();
1731 ext_id != extension_ids.end(); ++ext_id) {
1732 if (GetInstallTime(*ext_id) == base::Time()) {
1733 VLOG(1) << "Could not parse installation time of extension "
1734 << *ext_id << ". It was probably installed before setting "
1735 << kPrefInstallTime << " was introduced. Updating "
1736 << kPrefInstallTime << " to the current time.";
1737 const base::Time install_time = time_provider_->GetCurrentTime();
1738 UpdateExtensionPref(*ext_id,
1739 kPrefInstallTime,
1740 new base::StringValue(base::Int64ToString(
1741 install_time.ToInternalValue())));
1746 void ExtensionPrefs::InitPrefStore() {
1747 TRACE_EVENT0("browser,startup", "ExtensionPrefs::InitPrefStore")
1748 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefStoreTime");
1750 if (extensions_disabled_) {
1751 extension_pref_value_map_->NotifyInitializationCompleted();
1752 return;
1755 // When this is called, the PrefService is initialized and provides access
1756 // to the user preferences stored in a JSON file.
1757 ExtensionIdList extension_ids;
1759 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitPrefGetExtensionsTime");
1760 GetExtensions(&extension_ids);
1762 // Create empty preferences dictionary for each extension (these dictionaries
1763 // are pruned when persisting the preferences to disk).
1764 for (ExtensionIdList::iterator ext_id = extension_ids.begin();
1765 ext_id != extension_ids.end(); ++ext_id) {
1766 ScopedExtensionPrefUpdate update(prefs_, *ext_id);
1767 // This creates an empty dictionary if none is stored.
1768 update.Get();
1771 FixMissingPrefs(extension_ids);
1772 MigratePermissions(extension_ids);
1773 MigrateDisableReasons(extension_ids);
1775 InitExtensionControlledPrefs(extension_pref_value_map_);
1777 extension_pref_value_map_->NotifyInitializationCompleted();
1780 bool ExtensionPrefs::HasIncognitoPrefValue(const std::string& pref_key) const {
1781 bool has_incognito_pref_value = false;
1782 extension_pref_value_map_->GetEffectivePrefValue(pref_key,
1783 true,
1784 &has_incognito_pref_value);
1785 return has_incognito_pref_value;
1788 const base::DictionaryValue* ExtensionPrefs::GetGeometryCache(
1789 const std::string& extension_id) const {
1790 const base::DictionaryValue* extension_prefs = GetExtensionPref(extension_id);
1791 if (!extension_prefs)
1792 return NULL;
1794 const base::DictionaryValue* ext = NULL;
1795 if (!extension_prefs->GetDictionary(kPrefGeometryCache, &ext))
1796 return NULL;
1798 return ext;
1801 void ExtensionPrefs::SetGeometryCache(
1802 const std::string& extension_id,
1803 scoped_ptr<base::DictionaryValue> cache) {
1804 UpdateExtensionPref(extension_id, kPrefGeometryCache, cache.release());
1807 const base::DictionaryValue* ExtensionPrefs::GetInstallSignature() const {
1808 return prefs_->GetDictionary(kInstallSignature);
1811 void ExtensionPrefs::SetInstallSignature(
1812 const base::DictionaryValue* signature) {
1813 if (signature) {
1814 prefs_->Set(kInstallSignature, *signature);
1815 DVLOG(1) << "SetInstallSignature - saving";
1816 } else {
1817 DVLOG(1) << "SetInstallSignature - clearing";
1818 prefs_->ClearPref(kInstallSignature);
1822 std::string ExtensionPrefs::GetInstallParam(
1823 const std::string& extension_id) const {
1824 const base::DictionaryValue* extension = GetExtensionPref(extension_id);
1825 if (!extension) // Expected during unit testing.
1826 return std::string();
1827 std::string install_parameter;
1828 if (!extension->GetString(kPrefInstallParam, &install_parameter))
1829 return std::string();
1830 return install_parameter;
1833 void ExtensionPrefs::SetInstallParam(const std::string& extension_id,
1834 const std::string& install_parameter) {
1835 UpdateExtensionPref(extension_id,
1836 kPrefInstallParam,
1837 new base::StringValue(install_parameter));
1840 int ExtensionPrefs::GetCorruptedDisableCount() const {
1841 return prefs_->GetInteger(kCorruptedDisableCount);
1844 void ExtensionPrefs::IncrementCorruptedDisableCount() {
1845 int count = prefs_->GetInteger(kCorruptedDisableCount);
1846 prefs_->SetInteger(kCorruptedDisableCount, count + 1);
1849 bool ExtensionPrefs::NeedsSync(const std::string& extension_id) const {
1850 return ReadPrefAsBooleanAndReturn(extension_id, kPrefNeedsSync);
1853 void ExtensionPrefs::SetNeedsSync(const std::string& extension_id,
1854 bool needs_sync) {
1855 UpdateExtensionPref(extension_id, kPrefNeedsSync,
1856 needs_sync ? new base::FundamentalValue(true) : nullptr);
1859 ExtensionPrefs::ExtensionPrefs(
1860 content::BrowserContext* browser_context,
1861 PrefService* prefs,
1862 const base::FilePath& root_dir,
1863 ExtensionPrefValueMap* extension_pref_value_map,
1864 scoped_ptr<TimeProvider> time_provider,
1865 bool extensions_disabled,
1866 const std::vector<ExtensionPrefsObserver*>& early_observers)
1867 : browser_context_(browser_context),
1868 prefs_(prefs),
1869 install_directory_(root_dir),
1870 extension_pref_value_map_(extension_pref_value_map),
1871 time_provider_(time_provider.Pass()),
1872 extensions_disabled_(extensions_disabled) {
1873 MakePathsRelative();
1875 // Ensure that any early observers are watching before prefs are initialized.
1876 for (std::vector<ExtensionPrefsObserver*>::const_iterator iter =
1877 early_observers.begin();
1878 iter != early_observers.end();
1879 ++iter) {
1880 AddObserver(*iter);
1883 InitPrefStore();
1886 AppSorting* ExtensionPrefs::app_sorting() const {
1887 return ExtensionSystem::Get(browser_context_)->app_sorting();
1890 void ExtensionPrefs::SetNeedsStorageGarbageCollection(bool value) {
1891 prefs_->SetBoolean(pref_names::kStorageGarbageCollect, value);
1894 bool ExtensionPrefs::NeedsStorageGarbageCollection() const {
1895 return prefs_->GetBoolean(pref_names::kStorageGarbageCollect);
1898 // static
1899 void ExtensionPrefs::RegisterProfilePrefs(
1900 user_prefs::PrefRegistrySyncable* registry) {
1901 registry->RegisterDictionaryPref(pref_names::kExtensions);
1902 registry->RegisterListPref(pref_names::kToolbar,
1903 user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
1904 registry->RegisterIntegerPref(pref_names::kToolbarSize, -1);
1905 registry->RegisterDictionaryPref(kExtensionsBlacklistUpdate);
1906 registry->RegisterListPref(pref_names::kInstallAllowList);
1907 registry->RegisterListPref(pref_names::kInstallDenyList);
1908 registry->RegisterDictionaryPref(pref_names::kInstallForceList);
1909 registry->RegisterListPref(pref_names::kAllowedTypes);
1910 registry->RegisterBooleanPref(pref_names::kStorageGarbageCollect, false);
1911 registry->RegisterInt64Pref(pref_names::kLastUpdateCheck, 0);
1912 registry->RegisterInt64Pref(pref_names::kNextUpdateCheck, 0);
1913 registry->RegisterListPref(pref_names::kAllowedInstallSites);
1914 registry->RegisterStringPref(pref_names::kLastChromeVersion, std::string());
1915 registry->RegisterDictionaryPref(kInstallSignature);
1917 registry->RegisterListPref(pref_names::kNativeMessagingBlacklist);
1918 registry->RegisterListPref(pref_names::kNativeMessagingWhitelist);
1919 registry->RegisterBooleanPref(pref_names::kNativeMessagingUserLevelHosts,
1920 true);
1921 registry->RegisterIntegerPref(kCorruptedDisableCount, 0);
1923 #if !defined(OS_MACOSX)
1924 registry->RegisterBooleanPref(pref_names::kAppFullscreenAllowed, true);
1925 #endif
1928 template <class ExtensionIdContainer>
1929 bool ExtensionPrefs::GetUserExtensionPrefIntoContainer(
1930 const char* pref,
1931 ExtensionIdContainer* id_container_out) const {
1932 DCHECK(id_container_out->empty());
1934 const base::Value* user_pref_value = prefs_->GetUserPrefValue(pref);
1935 const base::ListValue* user_pref_as_list;
1936 if (!user_pref_value || !user_pref_value->GetAsList(&user_pref_as_list))
1937 return false;
1939 std::insert_iterator<ExtensionIdContainer> insert_iterator(
1940 *id_container_out, id_container_out->end());
1941 std::string extension_id;
1942 for (base::ListValue::const_iterator value_it = user_pref_as_list->begin();
1943 value_it != user_pref_as_list->end(); ++value_it) {
1944 if (!(*value_it)->GetAsString(&extension_id)) {
1945 NOTREACHED();
1946 continue;
1948 insert_iterator = extension_id;
1950 return true;
1953 template <class ExtensionIdContainer>
1954 void ExtensionPrefs::SetExtensionPrefFromContainer(
1955 const char* pref,
1956 const ExtensionIdContainer& strings) {
1957 ListPrefUpdate update(prefs_, pref);
1958 base::ListValue* list_of_values = update.Get();
1959 list_of_values->Clear();
1960 for (typename ExtensionIdContainer::const_iterator iter = strings.begin();
1961 iter != strings.end(); ++iter) {
1962 list_of_values->Append(new base::StringValue(*iter));
1966 void ExtensionPrefs::PopulateExtensionInfoPrefs(
1967 const Extension* extension,
1968 const base::Time install_time,
1969 Extension::State initial_state,
1970 int install_flags,
1971 const std::string& install_parameter,
1972 base::DictionaryValue* extension_dict) const {
1973 extension_dict->Set(kPrefState, new base::FundamentalValue(initial_state));
1974 extension_dict->Set(kPrefLocation,
1975 new base::FundamentalValue(extension->location()));
1976 extension_dict->Set(kPrefCreationFlags,
1977 new base::FundamentalValue(extension->creation_flags()));
1978 extension_dict->Set(kPrefFromWebStore,
1979 new base::FundamentalValue(extension->from_webstore()));
1980 extension_dict->Set(kPrefFromBookmark,
1981 new base::FundamentalValue(extension->from_bookmark()));
1982 extension_dict->Set(
1983 kPrefWasInstalledByDefault,
1984 new base::FundamentalValue(extension->was_installed_by_default()));
1985 extension_dict->Set(
1986 kPrefWasInstalledByOem,
1987 new base::FundamentalValue(extension->was_installed_by_oem()));
1988 extension_dict->Set(kPrefInstallTime,
1989 new base::StringValue(
1990 base::Int64ToString(install_time.ToInternalValue())));
1991 if (install_flags & kInstallFlagIsBlacklistedForMalware)
1992 extension_dict->Set(kPrefBlacklist, new base::FundamentalValue(true));
1994 if (install_flags & kInstallFlagIsEphemeral)
1995 extension_dict->Set(kPrefEphemeralApp, new base::FundamentalValue(true));
1996 else
1997 extension_dict->Remove(kPrefEphemeralApp, NULL);
1999 base::FilePath::StringType path = MakePathRelative(install_directory_,
2000 extension->path());
2001 extension_dict->Set(kPrefPath, new base::StringValue(path));
2002 if (!install_parameter.empty()) {
2003 extension_dict->Set(kPrefInstallParam,
2004 new base::StringValue(install_parameter));
2006 // We store prefs about LOAD extensions, but don't cache their manifest
2007 // since it may change on disk.
2008 if (!Manifest::IsUnpackedLocation(extension->location())) {
2009 extension_dict->Set(kPrefManifest,
2010 extension->manifest()->value()->DeepCopy());
2013 // Only writes kPrefDoNotSync when it is not the default.
2014 if (install_flags & kInstallFlagDoNotSync)
2015 extension_dict->Set(kPrefDoNotSync, new base::FundamentalValue(true));
2016 else
2017 extension_dict->Remove(kPrefDoNotSync, NULL);
2020 void ExtensionPrefs::InitExtensionControlledPrefs(
2021 ExtensionPrefValueMap* value_map) {
2022 TRACE_EVENT0("browser,startup",
2023 "ExtensionPrefs::InitExtensionControlledPrefs")
2024 SCOPED_UMA_HISTOGRAM_TIMER("Extensions.InitExtensionControlledPrefsTime");
2026 ExtensionIdList extension_ids;
2027 GetExtensions(&extension_ids);
2029 for (ExtensionIdList::iterator extension_id = extension_ids.begin();
2030 extension_id != extension_ids.end();
2031 ++extension_id) {
2032 base::Time install_time = GetInstallTime(*extension_id);
2033 bool is_enabled = !IsExtensionDisabled(*extension_id);
2034 bool is_incognito_enabled = IsIncognitoEnabled(*extension_id);
2035 value_map->RegisterExtension(
2036 *extension_id, install_time, is_enabled, is_incognito_enabled);
2038 FOR_EACH_OBSERVER(
2039 ExtensionPrefsObserver,
2040 observer_list_,
2041 OnExtensionRegistered(*extension_id, install_time, is_enabled));
2043 // Set regular extension controlled prefs.
2044 LoadExtensionControlledPrefs(
2045 this, value_map, *extension_id, kExtensionPrefsScopeRegular);
2046 // Set incognito extension controlled prefs.
2047 LoadExtensionControlledPrefs(this,
2048 value_map,
2049 *extension_id,
2050 kExtensionPrefsScopeIncognitoPersistent);
2051 // Set regular-only extension controlled prefs.
2052 LoadExtensionControlledPrefs(
2053 this, value_map, *extension_id, kExtensionPrefsScopeRegularOnly);
2055 FOR_EACH_OBSERVER(ExtensionPrefsObserver,
2056 observer_list_,
2057 OnExtensionPrefsLoaded(*extension_id, this));
2061 void ExtensionPrefs::FinishExtensionInfoPrefs(
2062 const std::string& extension_id,
2063 const base::Time install_time,
2064 bool needs_sort_ordinal,
2065 const syncer::StringOrdinal& suggested_page_ordinal,
2066 base::DictionaryValue* extension_dict) {
2067 // Reinitializes various preferences with empty dictionaries.
2068 if (!extension_dict->HasKey(pref_names::kPrefPreferences)) {
2069 extension_dict->Set(pref_names::kPrefPreferences,
2070 new base::DictionaryValue);
2073 if (!extension_dict->HasKey(pref_names::kPrefIncognitoPreferences)) {
2074 extension_dict->Set(pref_names::kPrefIncognitoPreferences,
2075 new base::DictionaryValue);
2078 if (!extension_dict->HasKey(pref_names::kPrefRegularOnlyPreferences)) {
2079 extension_dict->Set(pref_names::kPrefRegularOnlyPreferences,
2080 new base::DictionaryValue);
2083 if (!extension_dict->HasKey(pref_names::kPrefContentSettings))
2084 extension_dict->Set(pref_names::kPrefContentSettings, new base::ListValue);
2086 if (!extension_dict->HasKey(pref_names::kPrefIncognitoContentSettings)) {
2087 extension_dict->Set(pref_names::kPrefIncognitoContentSettings,
2088 new base::ListValue);
2091 // If this point has been reached, any pending installs should be considered
2092 // out of date.
2093 extension_dict->Remove(kDelayedInstallInfo, NULL);
2095 // Clear state that may be registered from a previous install.
2096 extension_dict->Remove(EventRouter::kRegisteredEvents, NULL);
2098 // FYI, all code below here races on sudden shutdown because |extension_dict|,
2099 // |app_sorting|, |extension_pref_value_map_|, and (potentially) observers
2100 // are updated non-transactionally. This is probably not fixable without
2101 // nested transactional updates to pref dictionaries.
2102 if (needs_sort_ordinal)
2103 app_sorting()->EnsureValidOrdinals(extension_id, suggested_page_ordinal);
2105 bool is_enabled = false;
2106 int initial_state;
2107 if (extension_dict->GetInteger(kPrefState, &initial_state)) {
2108 is_enabled = initial_state == Extension::ENABLED;
2110 bool is_incognito_enabled = IsIncognitoEnabled(extension_id);
2112 extension_pref_value_map_->RegisterExtension(
2113 extension_id, install_time, is_enabled, is_incognito_enabled);
2115 FOR_EACH_OBSERVER(
2116 ExtensionPrefsObserver,
2117 observer_list_,
2118 OnExtensionRegistered(extension_id, install_time, is_enabled));
2121 } // namespace extensions