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 "chrome/browser/prefs/profile_pref_store_manager.h"
7 #include "base/file_util.h"
8 #include "base/json/json_file_value_serializer.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram.h"
11 #include "base/prefs/json_pref_store.h"
12 #include "base/prefs/persistent_pref_store.h"
13 #include "base/prefs/pref_registry_simple.h"
14 #include "chrome/browser/prefs/pref_hash_store_impl.h"
15 #include "chrome/browser/prefs/tracked/pref_service_hash_store_contents.h"
16 #include "chrome/browser/prefs/tracked/segregated_pref_store.h"
17 #include "chrome/common/chrome_constants.h"
18 #include "chrome/common/pref_names.h"
19 #include "components/user_prefs/pref_registry_syncable.h"
23 // An adaptor that allows a PrefHashStoreImpl to access a preference store
24 // directly as a dictionary. Uses an equivalent layout to
25 // PrefStoreHashStoreContents.
26 class DictionaryHashStoreContents : public HashStoreContents {
28 // Instantiates a HashStoreContents that is a copy of |to_copy|. The copy is
29 // mutable but does not affect the original, nor is it persisted to disk in
31 explicit DictionaryHashStoreContents(const HashStoreContents& to_copy)
32 : hash_store_id_(to_copy.hash_store_id()),
33 super_mac_(to_copy.GetSuperMac()) {
34 if (to_copy.IsInitialized())
35 dictionary_.reset(to_copy.GetContents()->DeepCopy());
37 if (to_copy.GetVersion(&version))
38 version_.reset(new int(version));
41 // HashStoreContents implementation
42 virtual std::string hash_store_id() const OVERRIDE { return hash_store_id_; }
44 virtual void Reset() OVERRIDE {
50 virtual bool IsInitialized() const OVERRIDE {
54 virtual const base::DictionaryValue* GetContents() const OVERRIDE{
55 return dictionary_.get();
58 virtual scoped_ptr<MutableDictionary> GetMutableContents() OVERRIDE {
59 return scoped_ptr<MutableDictionary>(
60 new SimpleMutableDictionary(this));
63 virtual std::string GetSuperMac() const OVERRIDE { return super_mac_; }
65 virtual void SetSuperMac(const std::string& super_mac) OVERRIDE {
66 super_mac_ = super_mac;
69 virtual bool GetVersion(int* version) const OVERRIDE {
76 virtual void SetVersion(int version) OVERRIDE {
77 version_.reset(new int(version));
81 class SimpleMutableDictionary
82 : public HashStoreContents::MutableDictionary {
84 explicit SimpleMutableDictionary(DictionaryHashStoreContents* outer)
87 virtual ~SimpleMutableDictionary() {}
89 // MutableDictionary implementation
90 virtual base::DictionaryValue* operator->() OVERRIDE {
91 if (!outer_->dictionary_)
92 outer_->dictionary_.reset(new base::DictionaryValue);
93 return outer_->dictionary_.get();
97 DictionaryHashStoreContents* outer_;
99 DISALLOW_COPY_AND_ASSIGN(SimpleMutableDictionary);
102 const std::string hash_store_id_;
103 std::string super_mac_;
104 scoped_ptr<int> version_;
105 scoped_ptr<base::DictionaryValue> dictionary_;
107 DISALLOW_COPY_AND_ASSIGN(DictionaryHashStoreContents);
110 // An in-memory PrefStore backed by an immutable DictionaryValue.
111 class DictionaryPrefStore : public PrefStore {
113 explicit DictionaryPrefStore(const base::DictionaryValue* dictionary)
114 : dictionary_(dictionary) {}
116 virtual bool GetValue(const std::string& key,
117 const base::Value** result) const OVERRIDE {
118 const base::Value* tmp = NULL;
119 if (!dictionary_->Get(key, &tmp))
128 virtual ~DictionaryPrefStore() {}
130 const base::DictionaryValue* dictionary_;
132 DISALLOW_COPY_AND_ASSIGN(DictionaryPrefStore);
137 // TODO(erikwright): Enable this on Chrome OS and Android once MACs are moved
138 // out of Local State. This will resolve a race condition on Android and a
139 // privacy issue on ChromeOS. http://crbug.com/349158
140 const bool ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking =
141 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
147 // Waits for a PrefStore to be initialized and then initializes the
148 // corresponding PrefHashStore.
149 // The observer deletes itself when its work is completed.
150 class ProfilePrefStoreManager::InitializeHashStoreObserver
151 : public PrefStore::Observer {
153 // Creates an observer that will initialize |pref_hash_store| with the
154 // contents of |pref_store| when the latter is fully loaded.
155 InitializeHashStoreObserver(
156 const std::vector<PrefHashFilter::TrackedPreferenceMetadata>&
157 tracking_configuration,
158 size_t reporting_ids_count,
159 const scoped_refptr<PrefStore>& pref_store,
160 scoped_ptr<PrefHashStoreImpl> pref_hash_store_impl)
161 : tracking_configuration_(tracking_configuration),
162 reporting_ids_count_(reporting_ids_count),
163 pref_store_(pref_store),
164 pref_hash_store_impl_(pref_hash_store_impl.Pass()) {}
166 virtual ~InitializeHashStoreObserver();
168 // PrefStore::Observer implementation.
169 virtual void OnPrefValueChanged(const std::string& key) OVERRIDE;
170 virtual void OnInitializationCompleted(bool succeeded) OVERRIDE;
173 const std::vector<PrefHashFilter::TrackedPreferenceMetadata>
174 tracking_configuration_;
175 const size_t reporting_ids_count_;
176 scoped_refptr<PrefStore> pref_store_;
177 scoped_ptr<PrefHashStoreImpl> pref_hash_store_impl_;
179 DISALLOW_COPY_AND_ASSIGN(InitializeHashStoreObserver);
182 ProfilePrefStoreManager::InitializeHashStoreObserver::
183 ~InitializeHashStoreObserver() {}
185 void ProfilePrefStoreManager::InitializeHashStoreObserver::OnPrefValueChanged(
186 const std::string& key) {}
189 ProfilePrefStoreManager::InitializeHashStoreObserver::OnInitializationCompleted(
191 // If we successfully loaded the preferences _and_ the PrefHashStoreImpl
192 // hasn't been initialized by someone else in the meantime, initialize it now.
193 const PrefHashStoreImpl::StoreVersion pre_update_version =
194 pref_hash_store_impl_->GetCurrentVersion();
195 if (succeeded && pre_update_version < PrefHashStoreImpl::VERSION_LATEST) {
196 PrefHashFilter(pref_hash_store_impl_.PassAs<PrefHashStore>(),
197 tracking_configuration_,
198 reporting_ids_count_).Initialize(*pref_store_);
199 UMA_HISTOGRAM_ENUMERATION(
200 "Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
202 PrefHashStoreImpl::VERSION_LATEST + 1);
204 pref_store_->RemoveObserver(this);
208 ProfilePrefStoreManager::ProfilePrefStoreManager(
209 const base::FilePath& profile_path,
210 const std::vector<PrefHashFilter::TrackedPreferenceMetadata>&
211 tracking_configuration,
212 size_t reporting_ids_count,
213 const std::string& seed,
214 const std::string& device_id,
215 PrefService* local_state)
216 : profile_path_(profile_path),
217 tracking_configuration_(tracking_configuration),
218 reporting_ids_count_(reporting_ids_count),
220 device_id_(device_id),
221 local_state_(local_state) {}
223 ProfilePrefStoreManager::~ProfilePrefStoreManager() {}
226 void ProfilePrefStoreManager::RegisterPrefs(PrefRegistrySimple* registry) {
227 PrefServiceHashStoreContents::RegisterPrefs(registry);
231 void ProfilePrefStoreManager::RegisterProfilePrefs(
232 user_prefs::PrefRegistrySyncable* registry) {
233 PrefHashFilter::RegisterProfilePrefs(registry);
237 base::FilePath ProfilePrefStoreManager::GetPrefFilePathFromProfilePath(
238 const base::FilePath& profile_path) {
239 return profile_path.Append(chrome::kPreferencesFilename);
243 void ProfilePrefStoreManager::ResetAllPrefHashStores(PrefService* local_state) {
244 PrefServiceHashStoreContents::ResetAllPrefHashStores(local_state);
248 base::Time ProfilePrefStoreManager::GetResetTime(PrefService* pref_service) {
249 // It's a bit of a coincidence that this (and ClearResetTime) work(s). The
250 // PrefHashFilter attached to the protected pref store will store the reset
251 // time directly in the protected pref store without going through the
252 // SegregatedPrefStore.
254 // PrefHashFilter::GetResetTime will read the value through the pref service,
255 // and thus through the SegregatedPrefStore. Even though it's not listed as
256 // "protected" it will be read from the protected store prefentially to the
257 // (NULL) value in the unprotected pref store.
258 return PrefHashFilter::GetResetTime(pref_service);
262 void ProfilePrefStoreManager::ClearResetTime(PrefService* pref_service) {
263 // PrefHashFilter::ClearResetTime will clear the value through the pref
264 // service, and thus through the SegregatedPrefStore. Since it's not listed as
265 // "protected" it will be migrated from the protected store to the unprotected
266 // pref store before being deleted from the latter.
267 PrefHashFilter::ClearResetTime(pref_service);
270 void ProfilePrefStoreManager::ResetPrefHashStore() {
271 if (kPlatformSupportsPreferenceTracking)
272 GetPrefHashStoreImpl()->Reset();
275 PersistentPrefStore* ProfilePrefStoreManager::CreateProfilePrefStore(
276 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
277 scoped_ptr<PrefFilter> pref_filter;
278 if (!kPlatformSupportsPreferenceTracking) {
279 return new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
281 scoped_ptr<PrefFilter>());
284 std::vector<PrefHashFilter::TrackedPreferenceMetadata>
285 unprotected_configuration;
286 std::vector<PrefHashFilter::TrackedPreferenceMetadata>
287 protected_configuration;
288 std::set<std::string> protected_pref_names;
289 for (std::vector<PrefHashFilter::TrackedPreferenceMetadata>::const_iterator
290 it = tracking_configuration_.begin();
291 it != tracking_configuration_.end();
293 if (it->enforcement_level > PrefHashFilter::NO_ENFORCEMENT) {
294 protected_configuration.push_back(*it);
295 protected_pref_names.insert(it->name);
297 unprotected_configuration.push_back(*it);
301 scoped_ptr<PrefFilter> unprotected_pref_hash_filter(
302 new PrefHashFilter(GetPrefHashStoreImpl().PassAs<PrefHashStore>(),
303 unprotected_configuration,
304 reporting_ids_count_));
305 scoped_ptr<PrefFilter> protected_pref_hash_filter(
306 new PrefHashFilter(GetPrefHashStoreImpl().PassAs<PrefHashStore>(),
307 protected_configuration,
308 reporting_ids_count_));
310 scoped_refptr<PersistentPrefStore> unprotected_pref_store(
311 new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
313 unprotected_pref_hash_filter.Pass()));
314 scoped_refptr<PersistentPrefStore> protected_pref_store(new JsonPrefStore(
315 profile_path_.Append(chrome::kProtectedPreferencesFilename),
317 protected_pref_hash_filter.Pass()));
319 // The on_initialized callback is used to migrate newly protected values from
320 // the main Preferences store to the Protected Preferences store. It is also
321 // responsible for the initial migration to a two-store model.
322 return new SegregatedPrefStore(
323 unprotected_pref_store,
324 protected_pref_store,
325 protected_pref_names,
326 base::Bind(&PrefHashFilter::MigrateValues,
327 base::Owned(new PrefHashFilter(
329 protected_configuration,
330 reporting_ids_count_)),
331 unprotected_pref_store,
332 protected_pref_store));
335 void ProfilePrefStoreManager::UpdateProfileHashStoreIfRequired(
336 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
337 if (!kPlatformSupportsPreferenceTracking)
339 scoped_ptr<PrefHashStoreImpl> pref_hash_store_impl(GetPrefHashStoreImpl());
340 const PrefHashStoreImpl::StoreVersion current_version =
341 pref_hash_store_impl->GetCurrentVersion();
342 UMA_HISTOGRAM_ENUMERATION("Settings.TrackedPreferencesAlternateStoreVersion",
344 PrefHashStoreImpl::VERSION_LATEST + 1);
346 // Update the pref hash store if it's not at the latest version.
347 if (current_version != PrefHashStoreImpl::VERSION_LATEST) {
348 scoped_refptr<JsonPrefStore> pref_store =
349 new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
351 scoped_ptr<PrefFilter>());
352 pref_store->AddObserver(
353 new InitializeHashStoreObserver(tracking_configuration_,
354 reporting_ids_count_,
356 pref_hash_store_impl.Pass()));
357 pref_store->ReadPrefsAsync(NULL);
361 bool ProfilePrefStoreManager::InitializePrefsFromMasterPrefs(
362 const base::DictionaryValue& master_prefs) {
363 // Create the profile directory if it doesn't exist yet (very possible on
365 if (!base::CreateDirectory(profile_path_))
368 // This will write out to a single combined file which will be immediately
369 // migrated to two files on load.
370 JSONFileValueSerializer serializer(
371 GetPrefFilePathFromProfilePath(profile_path_));
373 // Call Serialize (which does IO) on the main thread, which would _normally_
374 // be verboten. In this case however, we require this IO to synchronously
375 // complete before Chrome can start (as master preferences seed the Local
376 // State and Preferences files). This won't trip ThreadIORestrictions as they
377 // won't have kicked in yet on the main thread.
378 bool success = serializer.Serialize(master_prefs);
380 if (success && kPlatformSupportsPreferenceTracking) {
381 scoped_refptr<const PrefStore> pref_store(
382 new DictionaryPrefStore(&master_prefs));
383 PrefHashFilter(GetPrefHashStoreImpl().PassAs<PrefHashStore>(),
384 tracking_configuration_,
385 reporting_ids_count_).Initialize(*pref_store);
388 UMA_HISTOGRAM_BOOLEAN("Settings.InitializedFromMasterPrefs", success);
393 ProfilePrefStoreManager::CreateDeprecatedCombinedProfilePrefStore(
394 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
395 scoped_ptr<PrefFilter> pref_filter;
396 if (kPlatformSupportsPreferenceTracking) {
398 new PrefHashFilter(GetPrefHashStoreImpl().PassAs<PrefHashStore>(),
399 tracking_configuration_,
400 reporting_ids_count_));
402 return new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
407 scoped_ptr<PrefHashStoreImpl> ProfilePrefStoreManager::GetPrefHashStoreImpl() {
408 DCHECK(kPlatformSupportsPreferenceTracking);
410 return make_scoped_ptr(new PrefHashStoreImpl(
413 scoped_ptr<HashStoreContents>(new PrefServiceHashStoreContents(
414 profile_path_.AsUTF8Unsafe(), local_state_))));
417 scoped_ptr<PrefHashStore> ProfilePrefStoreManager::CopyPrefHashStore() {
418 DCHECK(kPlatformSupportsPreferenceTracking);
420 PrefServiceHashStoreContents real_contents(profile_path_.AsUTF8Unsafe(),
422 return scoped_ptr<PrefHashStore>(new PrefHashStoreImpl(
425 scoped_ptr<HashStoreContents>(
426 new DictionaryHashStoreContents(real_contents))));