Upstream version 7.35.139.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / prefs / profile_pref_store_manager.cc
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.
4
5 #include "chrome/browser/prefs/profile_pref_store_manager.h"
6
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"
20
21 namespace {
22
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 {
27  public:
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
30   // any other way.
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());
36     int version = 0;
37     if (to_copy.GetVersion(&version))
38       version_.reset(new int(version));
39   }
40
41   // HashStoreContents implementation
42   virtual std::string hash_store_id() const OVERRIDE { return hash_store_id_; }
43
44   virtual void Reset() OVERRIDE {
45     dictionary_.reset();
46     super_mac_.clear();
47     version_.reset();
48   }
49
50   virtual bool IsInitialized() const OVERRIDE {
51     return dictionary_;
52   }
53
54   virtual const base::DictionaryValue* GetContents() const OVERRIDE{
55     return dictionary_.get();
56   }
57
58   virtual scoped_ptr<MutableDictionary> GetMutableContents() OVERRIDE {
59     return scoped_ptr<MutableDictionary>(
60         new SimpleMutableDictionary(this));
61   }
62
63   virtual std::string GetSuperMac() const OVERRIDE { return super_mac_; }
64
65   virtual void SetSuperMac(const std::string& super_mac) OVERRIDE {
66     super_mac_ = super_mac;
67   }
68
69   virtual bool GetVersion(int* version) const OVERRIDE {
70     if (!version_)
71       return false;
72     *version = *version_;
73     return true;
74   }
75
76   virtual void SetVersion(int version) OVERRIDE {
77     version_.reset(new int(version));
78   }
79
80  private:
81   class SimpleMutableDictionary
82       : public HashStoreContents::MutableDictionary {
83    public:
84     explicit SimpleMutableDictionary(DictionaryHashStoreContents* outer)
85         : outer_(outer) {}
86
87     virtual ~SimpleMutableDictionary() {}
88
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();
94     }
95
96    private:
97     DictionaryHashStoreContents* outer_;
98
99     DISALLOW_COPY_AND_ASSIGN(SimpleMutableDictionary);
100   };
101
102   const std::string hash_store_id_;
103   std::string super_mac_;
104   scoped_ptr<int> version_;
105   scoped_ptr<base::DictionaryValue> dictionary_;
106
107   DISALLOW_COPY_AND_ASSIGN(DictionaryHashStoreContents);
108 };
109
110 // An in-memory PrefStore backed by an immutable DictionaryValue.
111 class DictionaryPrefStore : public PrefStore {
112  public:
113   explicit DictionaryPrefStore(const base::DictionaryValue* dictionary)
114       : dictionary_(dictionary) {}
115
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))
120       return false;
121
122     if (result)
123       *result = tmp;
124     return true;
125   }
126
127  private:
128   virtual ~DictionaryPrefStore() {}
129
130   const base::DictionaryValue* dictionary_;
131
132   DISALLOW_COPY_AND_ASSIGN(DictionaryPrefStore);
133 };
134
135 }  // namespace
136
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)
142     false;
143 #else
144     true;
145 #endif
146
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 {
152  public:
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()) {}
165
166   virtual ~InitializeHashStoreObserver();
167
168   // PrefStore::Observer implementation.
169   virtual void OnPrefValueChanged(const std::string& key) OVERRIDE;
170   virtual void OnInitializationCompleted(bool succeeded) OVERRIDE;
171
172  private:
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_;
178
179   DISALLOW_COPY_AND_ASSIGN(InitializeHashStoreObserver);
180 };
181
182 ProfilePrefStoreManager::InitializeHashStoreObserver::
183     ~InitializeHashStoreObserver() {}
184
185 void ProfilePrefStoreManager::InitializeHashStoreObserver::OnPrefValueChanged(
186     const std::string& key) {}
187
188 void
189 ProfilePrefStoreManager::InitializeHashStoreObserver::OnInitializationCompleted(
190     bool succeeded) {
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",
201         pre_update_version,
202         PrefHashStoreImpl::VERSION_LATEST + 1);
203   }
204   pref_store_->RemoveObserver(this);
205   delete this;
206 }
207
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),
219       seed_(seed),
220       device_id_(device_id),
221       local_state_(local_state) {}
222
223 ProfilePrefStoreManager::~ProfilePrefStoreManager() {}
224
225 // static
226 void ProfilePrefStoreManager::RegisterPrefs(PrefRegistrySimple* registry) {
227   PrefServiceHashStoreContents::RegisterPrefs(registry);
228 }
229
230 // static
231 void ProfilePrefStoreManager::RegisterProfilePrefs(
232     user_prefs::PrefRegistrySyncable* registry) {
233   PrefHashFilter::RegisterProfilePrefs(registry);
234 }
235
236 // static
237 base::FilePath ProfilePrefStoreManager::GetPrefFilePathFromProfilePath(
238     const base::FilePath& profile_path) {
239   return profile_path.Append(chrome::kPreferencesFilename);
240 }
241
242 // static
243 void ProfilePrefStoreManager::ResetAllPrefHashStores(PrefService* local_state) {
244   PrefServiceHashStoreContents::ResetAllPrefHashStores(local_state);
245 }
246
247 //  static
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.
253
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);
259 }
260
261 // static
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);
268 }
269
270 void ProfilePrefStoreManager::ResetPrefHashStore() {
271   if (kPlatformSupportsPreferenceTracking)
272     GetPrefHashStoreImpl()->Reset();
273 }
274
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_),
280                              io_task_runner,
281                              scoped_ptr<PrefFilter>());
282   }
283
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();
292        ++it) {
293     if (it->enforcement_level > PrefHashFilter::NO_ENFORCEMENT) {
294       protected_configuration.push_back(*it);
295       protected_pref_names.insert(it->name);
296     } else {
297       unprotected_configuration.push_back(*it);
298     }
299   }
300
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_));
309
310   scoped_refptr<PersistentPrefStore> unprotected_pref_store(
311       new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
312                         io_task_runner,
313                         unprotected_pref_hash_filter.Pass()));
314   scoped_refptr<PersistentPrefStore> protected_pref_store(new JsonPrefStore(
315       profile_path_.Append(chrome::kProtectedPreferencesFilename),
316       io_task_runner,
317       protected_pref_hash_filter.Pass()));
318
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(
328                      CopyPrefHashStore(),
329                      protected_configuration,
330                      reporting_ids_count_)),
331                  unprotected_pref_store,
332                  protected_pref_store));
333 }
334
335 void ProfilePrefStoreManager::UpdateProfileHashStoreIfRequired(
336     const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
337   if (!kPlatformSupportsPreferenceTracking)
338     return;
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",
343                             current_version,
344                             PrefHashStoreImpl::VERSION_LATEST + 1);
345
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_),
350                           io_task_runner,
351                           scoped_ptr<PrefFilter>());
352     pref_store->AddObserver(
353         new InitializeHashStoreObserver(tracking_configuration_,
354                                         reporting_ids_count_,
355                                         pref_store,
356                                         pref_hash_store_impl.Pass()));
357     pref_store->ReadPrefsAsync(NULL);
358   }
359 }
360
361 bool ProfilePrefStoreManager::InitializePrefsFromMasterPrefs(
362     const base::DictionaryValue& master_prefs) {
363   // Create the profile directory if it doesn't exist yet (very possible on
364   // first run).
365   if (!base::CreateDirectory(profile_path_))
366     return false;
367
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_));
372
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);
379
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);
386   }
387
388   UMA_HISTOGRAM_BOOLEAN("Settings.InitializedFromMasterPrefs", success);
389   return success;
390 }
391
392 PersistentPrefStore*
393 ProfilePrefStoreManager::CreateDeprecatedCombinedProfilePrefStore(
394     const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
395   scoped_ptr<PrefFilter> pref_filter;
396   if (kPlatformSupportsPreferenceTracking) {
397     pref_filter.reset(
398         new PrefHashFilter(GetPrefHashStoreImpl().PassAs<PrefHashStore>(),
399                            tracking_configuration_,
400                            reporting_ids_count_));
401   }
402   return new JsonPrefStore(GetPrefFilePathFromProfilePath(profile_path_),
403                            io_task_runner,
404                            pref_filter.Pass());
405 }
406
407 scoped_ptr<PrefHashStoreImpl> ProfilePrefStoreManager::GetPrefHashStoreImpl() {
408   DCHECK(kPlatformSupportsPreferenceTracking);
409
410   return make_scoped_ptr(new PrefHashStoreImpl(
411       seed_,
412       device_id_,
413       scoped_ptr<HashStoreContents>(new PrefServiceHashStoreContents(
414           profile_path_.AsUTF8Unsafe(), local_state_))));
415 }
416
417 scoped_ptr<PrefHashStore> ProfilePrefStoreManager::CopyPrefHashStore() {
418   DCHECK(kPlatformSupportsPreferenceTracking);
419
420   PrefServiceHashStoreContents real_contents(profile_path_.AsUTF8Unsafe(),
421                                              local_state_);
422   return scoped_ptr<PrefHashStore>(new PrefHashStoreImpl(
423       seed_,
424       device_id_,
425       scoped_ptr<HashStoreContents>(
426           new DictionaryHashStoreContents(real_contents))));
427 }