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"
8 #include "base/file_util.h"
9 #include "base/json/json_file_value_serializer.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/prefs/json_pref_store.h"
13 #include "base/prefs/persistent_pref_store.h"
14 #include "base/prefs/pref_registry_simple.h"
15 #include "chrome/browser/prefs/pref_hash_store_impl.h"
16 #include "chrome/browser/prefs/tracked/pref_service_hash_store_contents.h"
17 #include "chrome/browser/prefs/tracked/segregated_pref_store.h"
18 #include "chrome/browser/prefs/tracked/tracked_preferences_migration.h"
19 #include "chrome/common/chrome_constants.h"
20 #include "chrome/common/pref_names.h"
21 #include "components/pref_registry/pref_registry_syncable.h"
25 // An adaptor that allows a PrefHashStoreImpl to access a preference store
26 // directly as a dictionary. Uses an equivalent layout to
27 // PrefStoreHashStoreContents.
28 class DictionaryHashStoreContents
: public HashStoreContents
{
30 // Instantiates a HashStoreContents that is a copy of |to_copy|. The copy is
31 // mutable but does not affect the original, nor is it persisted to disk in
33 explicit DictionaryHashStoreContents(const HashStoreContents
& to_copy
)
34 : hash_store_id_(to_copy
.hash_store_id()),
35 super_mac_(to_copy
.GetSuperMac()) {
36 if (to_copy
.IsInitialized())
37 dictionary_
.reset(to_copy
.GetContents()->DeepCopy());
39 if (to_copy
.GetVersion(&version
))
40 version_
.reset(new int(version
));
43 // HashStoreContents implementation
44 virtual std::string
hash_store_id() const OVERRIDE
{ return hash_store_id_
; }
46 virtual void Reset() OVERRIDE
{
52 virtual bool IsInitialized() const OVERRIDE
{
56 virtual const base::DictionaryValue
* GetContents() const OVERRIDE
{
57 return dictionary_
.get();
60 virtual scoped_ptr
<MutableDictionary
> GetMutableContents() OVERRIDE
{
61 return scoped_ptr
<MutableDictionary
>(
62 new SimpleMutableDictionary(this));
65 virtual std::string
GetSuperMac() const OVERRIDE
{ return super_mac_
; }
67 virtual void SetSuperMac(const std::string
& super_mac
) OVERRIDE
{
68 super_mac_
= super_mac
;
71 virtual bool GetVersion(int* version
) const OVERRIDE
{
78 virtual void SetVersion(int version
) OVERRIDE
{
79 version_
.reset(new int(version
));
82 virtual void CommitPendingWrite() OVERRIDE
{}
85 class SimpleMutableDictionary
86 : public HashStoreContents::MutableDictionary
{
88 explicit SimpleMutableDictionary(DictionaryHashStoreContents
* outer
)
91 virtual ~SimpleMutableDictionary() {}
93 // MutableDictionary implementation
94 virtual base::DictionaryValue
* operator->() OVERRIDE
{
95 if (!outer_
->dictionary_
)
96 outer_
->dictionary_
.reset(new base::DictionaryValue
);
97 return outer_
->dictionary_
.get();
101 DictionaryHashStoreContents
* outer_
;
103 DISALLOW_COPY_AND_ASSIGN(SimpleMutableDictionary
);
106 const std::string hash_store_id_
;
107 std::string super_mac_
;
108 scoped_ptr
<int> version_
;
109 scoped_ptr
<base::DictionaryValue
> dictionary_
;
111 DISALLOW_COPY_AND_ASSIGN(DictionaryHashStoreContents
);
114 // An in-memory PrefStore backed by an immutable DictionaryValue.
115 class DictionaryPrefStore
: public PrefStore
{
117 explicit DictionaryPrefStore(const base::DictionaryValue
* dictionary
)
118 : dictionary_(dictionary
) {}
120 virtual bool GetValue(const std::string
& key
,
121 const base::Value
** result
) const OVERRIDE
{
122 const base::Value
* tmp
= NULL
;
123 if (!dictionary_
->Get(key
, &tmp
))
132 virtual ~DictionaryPrefStore() {}
134 const base::DictionaryValue
* dictionary_
;
136 DISALLOW_COPY_AND_ASSIGN(DictionaryPrefStore
);
139 // Waits for a PrefStore to be initialized and then initializes the
140 // corresponding PrefHashStore.
141 // The observer deletes itself when its work is completed.
142 class InitializeHashStoreObserver
: public PrefStore::Observer
{
144 // Creates an observer that will initialize |pref_hash_store| with the
145 // contents of |pref_store| when the latter is fully loaded.
146 InitializeHashStoreObserver(
147 const std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>&
148 tracking_configuration
,
149 size_t reporting_ids_count
,
150 const scoped_refptr
<PrefStore
>& pref_store
,
151 scoped_ptr
<PrefHashStoreImpl
> pref_hash_store_impl
)
152 : tracking_configuration_(tracking_configuration
),
153 reporting_ids_count_(reporting_ids_count
),
154 pref_store_(pref_store
),
155 pref_hash_store_impl_(pref_hash_store_impl
.Pass()) {}
157 virtual ~InitializeHashStoreObserver();
159 // PrefStore::Observer implementation.
160 virtual void OnPrefValueChanged(const std::string
& key
) OVERRIDE
;
161 virtual void OnInitializationCompleted(bool succeeded
) OVERRIDE
;
164 const std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>
165 tracking_configuration_
;
166 const size_t reporting_ids_count_
;
167 scoped_refptr
<PrefStore
> pref_store_
;
168 scoped_ptr
<PrefHashStoreImpl
> pref_hash_store_impl_
;
170 DISALLOW_COPY_AND_ASSIGN(InitializeHashStoreObserver
);
173 InitializeHashStoreObserver::~InitializeHashStoreObserver() {}
175 void InitializeHashStoreObserver::OnPrefValueChanged(const std::string
& key
) {}
177 void InitializeHashStoreObserver::OnInitializationCompleted(bool succeeded
) {
178 // If we successfully loaded the preferences _and_ the PrefHashStoreImpl
179 // hasn't been initialized by someone else in the meantime, initialize it now.
180 const PrefHashStoreImpl::StoreVersion pre_update_version
=
181 pref_hash_store_impl_
->GetCurrentVersion();
182 if (succeeded
&& pre_update_version
< PrefHashStoreImpl::VERSION_LATEST
) {
183 PrefHashFilter(pref_hash_store_impl_
.PassAs
<PrefHashStore
>(),
184 tracking_configuration_
,
186 reporting_ids_count_
).Initialize(*pref_store_
);
187 UMA_HISTOGRAM_ENUMERATION(
188 "Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
190 PrefHashStoreImpl::VERSION_LATEST
+ 1);
192 pref_store_
->RemoveObserver(this);
198 // TODO(erikwright): Enable this on Chrome OS and Android once MACs are moved
199 // out of Local State. This will resolve a race condition on Android and a
200 // privacy issue on ChromeOS. http://crbug.com/349158
201 const bool ProfilePrefStoreManager::kPlatformSupportsPreferenceTracking
=
202 #if defined(OS_ANDROID) || defined(OS_CHROMEOS)
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 return PrefHashFilter::GetResetTime(pref_service
);
253 void ProfilePrefStoreManager::ClearResetTime(PrefService
* pref_service
) {
254 PrefHashFilter::ClearResetTime(pref_service
);
257 void ProfilePrefStoreManager::ResetPrefHashStore() {
258 if (kPlatformSupportsPreferenceTracking
)
259 GetPrefHashStoreImpl()->Reset();
262 PersistentPrefStore
* ProfilePrefStoreManager::CreateProfilePrefStore(
263 const scoped_refptr
<base::SequencedTaskRunner
>& io_task_runner
,
264 TrackedPreferenceValidationDelegate
* validation_delegate
) {
265 scoped_ptr
<PrefFilter
> pref_filter
;
266 if (!kPlatformSupportsPreferenceTracking
) {
267 return new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_
),
269 scoped_ptr
<PrefFilter
>());
272 std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>
273 unprotected_configuration
;
274 std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>
275 protected_configuration
;
276 std::set
<std::string
> protected_pref_names
;
277 std::set
<std::string
> unprotected_pref_names
;
278 for (std::vector
<PrefHashFilter::TrackedPreferenceMetadata
>::const_iterator
279 it
= tracking_configuration_
.begin();
280 it
!= tracking_configuration_
.end();
282 if (it
->enforcement_level
> PrefHashFilter::NO_ENFORCEMENT
) {
283 protected_configuration
.push_back(*it
);
284 protected_pref_names
.insert(it
->name
);
286 unprotected_configuration
.push_back(*it
);
287 unprotected_pref_names
.insert(it
->name
);
291 scoped_ptr
<PrefHashFilter
> unprotected_pref_hash_filter(
292 new PrefHashFilter(GetPrefHashStoreImpl().PassAs
<PrefHashStore
>(),
293 unprotected_configuration
,
295 reporting_ids_count_
));
296 scoped_ptr
<PrefHashFilter
> protected_pref_hash_filter(
297 new PrefHashFilter(GetPrefHashStoreImpl().PassAs
<PrefHashStore
>(),
298 protected_configuration
,
300 reporting_ids_count_
));
302 PrefHashFilter
* raw_unprotected_pref_hash_filter
=
303 unprotected_pref_hash_filter
.get();
304 PrefHashFilter
* raw_protected_pref_hash_filter
=
305 protected_pref_hash_filter
.get();
307 scoped_refptr
<JsonPrefStore
> unprotected_pref_store(
308 new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_
),
310 unprotected_pref_hash_filter
.PassAs
<PrefFilter
>()));
311 scoped_refptr
<JsonPrefStore
> protected_pref_store(new JsonPrefStore(
312 profile_path_
.Append(chrome::kProtectedPreferencesFilename
),
314 protected_pref_hash_filter
.PassAs
<PrefFilter
>()));
316 SetupTrackedPreferencesMigration(
317 unprotected_pref_names
,
318 protected_pref_names
,
319 base::Bind(&JsonPrefStore::RemoveValueSilently
,
320 unprotected_pref_store
->AsWeakPtr()),
321 base::Bind(&JsonPrefStore::RemoveValueSilently
,
322 protected_pref_store
->AsWeakPtr()),
323 base::Bind(&JsonPrefStore::RegisterOnNextSuccessfulWriteCallback
,
324 unprotected_pref_store
->AsWeakPtr()),
325 base::Bind(&JsonPrefStore::RegisterOnNextSuccessfulWriteCallback
,
326 protected_pref_store
->AsWeakPtr()),
327 raw_unprotected_pref_hash_filter
,
328 raw_protected_pref_hash_filter
);
330 return new SegregatedPrefStore(unprotected_pref_store
, protected_pref_store
,
331 protected_pref_names
);
334 void ProfilePrefStoreManager::UpdateProfileHashStoreIfRequired(
335 const scoped_refptr
<base::SequencedTaskRunner
>& io_task_runner
) {
336 if (!kPlatformSupportsPreferenceTracking
)
338 scoped_ptr
<PrefHashStoreImpl
> pref_hash_store_impl(GetPrefHashStoreImpl());
339 const PrefHashStoreImpl::StoreVersion current_version
=
340 pref_hash_store_impl
->GetCurrentVersion();
341 UMA_HISTOGRAM_ENUMERATION("Settings.TrackedPreferencesAlternateStoreVersion",
343 PrefHashStoreImpl::VERSION_LATEST
+ 1);
345 // Update the pref hash store if it's not at the latest version.
346 if (current_version
!= PrefHashStoreImpl::VERSION_LATEST
) {
347 scoped_refptr
<JsonPrefStore
> pref_store
=
348 new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_
),
350 scoped_ptr
<PrefFilter
>());
351 pref_store
->AddObserver(
352 new InitializeHashStoreObserver(tracking_configuration_
,
353 reporting_ids_count_
,
355 pref_hash_store_impl
.Pass()));
356 pref_store
->ReadPrefsAsync(NULL
);
360 bool ProfilePrefStoreManager::InitializePrefsFromMasterPrefs(
361 const base::DictionaryValue
& master_prefs
) {
362 // Create the profile directory if it doesn't exist yet (very possible on
364 if (!base::CreateDirectory(profile_path_
))
367 // This will write out to a single combined file which will be immediately
368 // migrated to two files on load.
369 JSONFileValueSerializer
serializer(
370 GetPrefFilePathFromProfilePath(profile_path_
));
372 // Call Serialize (which does IO) on the main thread, which would _normally_
373 // be verboten. In this case however, we require this IO to synchronously
374 // complete before Chrome can start (as master preferences seed the Local
375 // State and Preferences files). This won't trip ThreadIORestrictions as they
376 // won't have kicked in yet on the main thread.
377 bool success
= serializer
.Serialize(master_prefs
);
379 if (success
&& kPlatformSupportsPreferenceTracking
) {
380 scoped_refptr
<const PrefStore
> pref_store(
381 new DictionaryPrefStore(&master_prefs
));
382 PrefHashFilter(GetPrefHashStoreImpl().PassAs
<PrefHashStore
>(),
383 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_
,
401 reporting_ids_count_
));
403 return new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_
),
408 scoped_ptr
<PrefHashStoreImpl
> ProfilePrefStoreManager::GetPrefHashStoreImpl() {
409 DCHECK(kPlatformSupportsPreferenceTracking
);
411 return make_scoped_ptr(new PrefHashStoreImpl(
414 scoped_ptr
<HashStoreContents
>(new PrefServiceHashStoreContents(
415 profile_path_
.AsUTF8Unsafe(), local_state_
))));