Upload upstream chromium 73.0.3683.0
[platform/framework/web/chromium-efl.git] / components / sync_preferences / pref_model_associator.cc
1 // Copyright (c) 2012 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 "components/sync_preferences/pref_model_associator.h"
6
7 #include <algorithm>
8 #include <iterator>
9 #include <memory>
10 #include <utility>
11
12 #include "base/auto_reset.h"
13 #include "base/json/json_reader.h"
14 #include "base/json/json_string_value_serializer.h"
15 #include "base/location.h"
16 #include "base/logging.h"
17 #include "base/memory/ptr_util.h"
18 #include "base/metrics/histogram_macros.h"
19 #include "base/stl_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "components/prefs/persistent_pref_store.h"
23 #include "components/prefs/pref_service.h"
24 #include "components/sync/model/sync_change.h"
25 #include "components/sync/model/sync_change_processor.h"
26 #include "components/sync/model/sync_error_factory.h"
27 #include "components/sync/protocol/preference_specifics.pb.h"
28 #include "components/sync/protocol/sync.pb.h"
29 #include "components/sync_preferences/pref_model_associator_client.h"
30 #include "components/sync_preferences/pref_service_syncable.h"
31 #include "components/sync_preferences/synced_pref_observer.h"
32
33 using syncer::PREFERENCES;
34 using syncer::PRIORITY_PREFERENCES;
35
36 namespace sync_preferences {
37
38 namespace {
39
40 const sync_pb::PreferenceSpecifics& GetSpecifics(const syncer::SyncData& pref) {
41   DCHECK(pref.GetDataType() == syncer::PREFERENCES ||
42          pref.GetDataType() == syncer::PRIORITY_PREFERENCES);
43   if (pref.GetDataType() == syncer::PRIORITY_PREFERENCES) {
44     return pref.GetSpecifics().priority_preference().preference();
45   } else {
46     return pref.GetSpecifics().preference();
47   }
48 }
49
50 sync_pb::PreferenceSpecifics* GetMutableSpecifics(
51     const syncer::ModelType type,
52     sync_pb::EntitySpecifics* specifics) {
53   if (type == syncer::PRIORITY_PREFERENCES) {
54     DCHECK(!specifics->has_preference());
55     return specifics->mutable_priority_preference()->mutable_preference();
56   } else {
57     DCHECK(!specifics->has_priority_preference());
58     return specifics->mutable_preference();
59   }
60 }
61
62 }  // namespace
63
64 PrefModelAssociator::PrefModelAssociator(
65     const PrefModelAssociatorClient* client,
66     syncer::ModelType type,
67     UnknownUserPrefAccessor* accessor)
68     : pref_accessor_(accessor), type_(type), client_(client) {
69   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
70   DCHECK(type_ == PREFERENCES || type_ == PRIORITY_PREFERENCES);
71 }
72
73 PrefModelAssociator::~PrefModelAssociator() {
74   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
75   pref_service_ = nullptr;
76
77   synced_pref_observers_.clear();
78 }
79
80 void PrefModelAssociator::InitPrefAndAssociate(
81     const syncer::SyncData& sync_pref,
82     const std::string& pref_name,
83     syncer::SyncChangeList* sync_changes) {
84   UnknownUserPrefAccessor::PreferenceState local_pref_state =
85       pref_accessor_->GetPreferenceState(type_, pref_name);
86   if (local_pref_state.registration_state ==
87           UnknownUserPrefAccessor::RegistrationState::kUnknown ||
88       local_pref_state.registration_state ==
89           UnknownUserPrefAccessor::RegistrationState::kNotSyncable) {
90     // Only process syncable prefs and unknown prefs if whitelisted.
91     return;
92   }
93   VLOG(1) << "Associating preference " << pref_name;
94
95   if (sync_pref.IsValid()) {
96     const sync_pb::PreferenceSpecifics& preference = GetSpecifics(sync_pref);
97     DCHECK(pref_name == preference.name());
98     base::JSONReader reader;
99     std::unique_ptr<base::Value> sync_value(
100         reader.ReadToValue(preference.value()));
101     if (!sync_value.get()) {
102       LOG(ERROR) << "Failed to deserialize value of preference '" << pref_name
103                  << "': " << reader.GetErrorMessage();
104       return;
105     }
106
107     if (local_pref_state.persisted_value) {
108       DVLOG(1) << "Found user pref value for " << pref_name;
109       // We have both server and local values. Merge them.
110       std::unique_ptr<base::Value> new_value(MergePreference(
111           pref_name, *local_pref_state.persisted_value, *sync_value));
112
113       // Update the local preference based on what we got from the
114       // sync server. Note: this only updates the user value store, which is
115       // ignored if the preference is policy controlled.
116       if (new_value->is_none()) {
117         LOG(WARNING) << "Sync has null value for pref " << pref_name.c_str();
118         pref_accessor_->ClearPref(pref_name, local_pref_state);
119       } else if (!local_pref_state.persisted_value->Equals(new_value.get())) {
120         pref_accessor_->SetPref(pref_name, local_pref_state, *new_value);
121       }
122
123       // If the merge resulted in an updated value, inform the syncer.
124       if (!sync_value->Equals(new_value.get())) {
125         syncer::SyncData sync_data;
126         if (!CreatePrefSyncData(pref_name, *new_value, &sync_data)) {
127           LOG(ERROR) << "Failed to update preference.";
128           return;
129         }
130
131         sync_changes->push_back(syncer::SyncChange(
132             FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
133       }
134     } else if (!sync_value->is_none()) {
135       // Only a server value exists. Just set the local user value.
136       pref_accessor_->SetPref(pref_name, local_pref_state, *sync_value);
137     } else {
138       LOG(WARNING) << "Sync has null value for pref " << pref_name.c_str();
139     }
140     synced_preferences_.insert(preference.name());
141   } else if (local_pref_state.persisted_value) {
142     DCHECK_EQ(local_pref_state.registration_state,
143               UnknownUserPrefAccessor::RegistrationState::kSyncable);
144     // The server does not know about this preference and should be added
145     // to the syncer's database.
146     syncer::SyncData sync_data;
147     if (!CreatePrefSyncData(pref_name, *local_pref_state.persisted_value,
148                             &sync_data)) {
149       LOG(ERROR) << "Failed to update preference.";
150       return;
151     }
152     sync_changes->push_back(syncer::SyncChange(
153         FROM_HERE, syncer::SyncChange::ACTION_ADD, sync_data));
154     synced_preferences_.insert(pref_name);
155   }
156
157   // Else this pref does not have a sync value but also does not have a user
158   // controlled value (either it's a default value or it's policy controlled,
159   // either way it's not interesting). We can ignore it. Once it gets changed,
160   // we'll send the new user controlled value to the syncer.
161 }
162
163 void PrefModelAssociator::RegisterMergeDataFinishedCallback(
164     const base::Closure& callback) {
165   if (!models_associated_)
166     callback_list_.push_back(callback);
167   else
168     callback.Run();
169 }
170
171 syncer::SyncMergeResult PrefModelAssociator::MergeDataAndStartSyncing(
172     syncer::ModelType type,
173     const syncer::SyncDataList& initial_sync_data,
174     std::unique_ptr<syncer::SyncChangeProcessor> sync_processor,
175     std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory) {
176   DCHECK_EQ(type_, type);
177   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
178   DCHECK(pref_service_);
179   DCHECK(!sync_processor_.get());
180   DCHECK(sync_processor.get());
181   DCHECK(sync_error_factory.get());
182   syncer::SyncMergeResult merge_result(type);
183   sync_processor_ = std::move(sync_processor);
184   sync_error_factory_ = std::move(sync_error_factory);
185
186   syncer::SyncChangeList new_changes;
187   std::set<std::string> remaining_preferences = registered_preferences_;
188
189   // Go through and check for all preferences we care about that sync already
190   // knows about.
191   for (auto sync_iter = initial_sync_data.begin();
192        sync_iter != initial_sync_data.end(); ++sync_iter) {
193     DCHECK_EQ(type_, sync_iter->GetDataType());
194
195     const sync_pb::PreferenceSpecifics& preference = GetSpecifics(*sync_iter);
196     std::string sync_pref_name = preference.name();
197     remaining_preferences.erase(sync_pref_name);
198     InitPrefAndAssociate(*sync_iter, sync_pref_name, &new_changes);
199   }
200
201   // Go through and build sync data for any remaining preferences.
202   for (auto pref_name_iter = remaining_preferences.begin();
203        pref_name_iter != remaining_preferences.end(); ++pref_name_iter) {
204     InitPrefAndAssociate(syncer::SyncData(), *pref_name_iter, &new_changes);
205   }
206
207   UMA_HISTOGRAM_COUNTS_1000("Sync.Preferences.SyncingUnknownPrefs",
208                             pref_accessor_->GetNumberOfSyncingUnknownPrefs());
209
210   // Push updates to sync.
211   merge_result.set_error(
212       sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
213   if (merge_result.error().IsSet())
214     return merge_result;
215
216   for (const auto& callback : callback_list_)
217     callback.Run();
218   callback_list_.clear();
219
220   models_associated_ = true;
221   pref_service_->OnIsSyncingChanged();
222   return merge_result;
223 }
224
225 void PrefModelAssociator::StopSyncing(syncer::ModelType type) {
226   DCHECK_EQ(type_, type);
227   models_associated_ = false;
228   sync_processor_.reset();
229   sync_error_factory_.reset();
230   pref_service_->OnIsSyncingChanged();
231 }
232
233 std::unique_ptr<base::Value> PrefModelAssociator::MergePreference(
234     const std::string& name,
235     const base::Value& local_value,
236     const base::Value& server_value) {
237   // This function special cases preferences individually, so don't attempt
238   // to merge for all migrated values.
239   if (client_) {
240     std::string new_pref_name;
241     if (client_->IsMergeableListPreference(name))
242       return MergeListValues(local_value, server_value);
243     if (client_->IsMergeableDictionaryPreference(name)) {
244       return std::make_unique<base::Value>(
245           MergeDictionaryValues(local_value, server_value));
246     }
247     std::unique_ptr<base::Value> merged_value =
248         client_->MaybeMergePreferenceValues(name, local_value, server_value);
249     if (merged_value)
250       return merged_value;
251   }
252
253   // If this is not a specially handled preference, server wins.
254   return base::WrapUnique(server_value.DeepCopy());
255 }
256
257 bool PrefModelAssociator::CreatePrefSyncData(
258     const std::string& name,
259     const base::Value& value,
260     syncer::SyncData* sync_data) const {
261   if (value.is_none()) {
262     LOG(ERROR) << "Attempting to sync a null pref value for " << name;
263     return false;
264   }
265
266   std::string serialized;
267   // TODO(zea): consider JSONWriter::Write since you don't have to check
268   // failures to deserialize.
269   JSONStringValueSerializer json(&serialized);
270   if (!json.Serialize(value)) {
271     LOG(ERROR) << "Failed to serialize preference value.";
272     return false;
273   }
274
275   sync_pb::EntitySpecifics specifics;
276   sync_pb::PreferenceSpecifics* pref_specifics =
277       GetMutableSpecifics(type_, &specifics);
278
279   pref_specifics->set_name(name);
280   pref_specifics->set_value(serialized);
281   *sync_data = syncer::SyncData::CreateLocalData(name, name, specifics);
282   return true;
283 }
284
285 std::unique_ptr<base::Value> PrefModelAssociator::MergeListValues(
286     const base::Value& from_value,
287     const base::Value& to_value) {
288   if (from_value.is_none())
289     return base::Value::ToUniquePtrValue(to_value.Clone());
290   if (to_value.is_none())
291     return base::Value::ToUniquePtrValue(from_value.Clone());
292
293   DCHECK(from_value.type() == base::Value::Type::LIST);
294   DCHECK(to_value.type() == base::Value::Type::LIST);
295
296   base::Value result = to_value.Clone();
297   base::Value::ListStorage& list = result.GetList();
298   for (const auto& value : from_value.GetList()) {
299     if (!base::ContainsValue(list, value))
300       list.emplace_back(value.Clone());
301   }
302
303   return base::Value::ToUniquePtrValue(std::move(result));
304 }
305
306 base::Value PrefModelAssociator::MergeDictionaryValues(
307     const base::Value& from_value,
308     const base::Value& to_value) {
309   if (from_value.is_none())
310     return to_value.Clone();
311   if (to_value.is_none())
312     return from_value.Clone();
313
314   DCHECK(from_value.is_dict());
315   DCHECK(to_value.is_dict());
316   base::Value result = to_value.Clone();
317
318   for (const auto& it : from_value.DictItems()) {
319     const base::Value* from_key_value = &it.second;
320     base::Value* to_key_value = result.FindKey(it.first);
321     if (to_key_value) {
322       if (from_key_value->is_dict() && to_key_value->is_dict()) {
323         *to_key_value = MergeDictionaryValues(*from_key_value, *to_key_value);
324       }
325       // Note that for all other types we want to preserve the "to"
326       // values so we do nothing here.
327     } else {
328       result.SetKey(it.first, from_key_value->Clone());
329     }
330   }
331   return result;
332 }
333
334 syncer::SyncDataList PrefModelAssociator::GetAllSyncData(
335     syncer::ModelType type) const {
336   DCHECK_EQ(type_, type);
337   syncer::SyncDataList current_data;
338   for (auto iter = synced_preferences_.begin();
339        iter != synced_preferences_.end(); ++iter) {
340     std::string name = *iter;
341     if (pref_accessor_->GetPreferenceState(type_, name).registration_state !=
342         UnknownUserPrefAccessor::RegistrationState::kSyncable) {
343       continue;
344     }
345     const PrefService::Preference* pref = pref_service_->FindPreference(name);
346     DCHECK(pref);
347     if (!pref->IsUserControlled() || pref->IsDefaultValue())
348       continue;  // This is not data we care about.
349     // TODO(zea): plumb a way to read the user controlled value.
350     syncer::SyncData sync_data;
351     if (!CreatePrefSyncData(name, *pref->GetValue(), &sync_data))
352       continue;
353     current_data.push_back(sync_data);
354   }
355   return current_data;
356 }
357
358 syncer::SyncError PrefModelAssociator::ProcessSyncChanges(
359     const base::Location& from_here,
360     const syncer::SyncChangeList& change_list) {
361   if (!models_associated_) {
362     syncer::SyncError error(FROM_HERE, syncer::SyncError::DATATYPE_ERROR,
363                             "Models not yet associated.", PREFERENCES);
364     return error;
365   }
366   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
367   syncer::SyncChangeList::const_iterator iter;
368   for (iter = change_list.begin(); iter != change_list.end(); ++iter) {
369     DCHECK_EQ(type_, iter->sync_data().GetDataType());
370
371     const sync_pb::PreferenceSpecifics& pref_specifics =
372         GetSpecifics(iter->sync_data());
373
374     UnknownUserPrefAccessor::PreferenceState local_pref_state =
375         pref_accessor_->GetPreferenceState(type_, pref_specifics.name());
376     if (local_pref_state.registration_state ==
377         UnknownUserPrefAccessor::RegistrationState::kUnknown) {
378       // It is possible that we may receive a change to a preference we do not
379       // want to sync. For example if the user is syncing a Mac client and a
380       // Windows client, the Windows client does not support
381       // kConfirmToQuitEnabled. Ignore updates from these preferences.
382       // We only sync such prefs if they are whitelisted.
383       continue;
384     }
385     if (local_pref_state.registration_state ==
386         UnknownUserPrefAccessor::RegistrationState::kNotSyncable) {
387       // Don't process remote changes for prefs this client doesn't want synced.
388       continue;
389     }
390     if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
391       pref_accessor_->ClearPref(pref_specifics.name(), local_pref_state);
392       continue;
393     }
394
395     std::unique_ptr<base::Value> new_value(
396         ReadPreferenceSpecifics(pref_specifics));
397     if (!new_value.get()) {
398       // Skip values we can't deserialize.
399       // TODO(zea): consider taking some further action such as erasing the
400       // bad data.
401       continue;
402     }
403
404     // This will only modify the user controlled value store, which takes
405     // priority over the default value but is ignored if the preference is
406     // policy controlled.
407     pref_accessor_->SetPref(pref_specifics.name(), local_pref_state,
408                             *new_value);
409
410     NotifySyncedPrefObservers(pref_specifics.name(), true /*from_sync*/);
411
412     // Keep track of any newly synced preferences. This can happen if a
413     // preference was late registered or remotely added (ACTION_ADD).
414     synced_preferences_.insert(pref_specifics.name());
415   }
416   return syncer::SyncError();
417 }
418
419 // static
420 base::Value* PrefModelAssociator::ReadPreferenceSpecifics(
421     const sync_pb::PreferenceSpecifics& preference) {
422   base::JSONReader reader;
423   std::unique_ptr<base::Value> value(reader.ReadToValue(preference.value()));
424   if (!value.get()) {
425     std::string err =
426         "Failed to deserialize preference value: " + reader.GetErrorMessage();
427     LOG(ERROR) << err;
428     return nullptr;
429   }
430   return value.release();
431 }
432
433 bool PrefModelAssociator::IsPrefSynced(const std::string& name) const {
434   return synced_preferences_.find(name) != synced_preferences_.end();
435 }
436
437 void PrefModelAssociator::AddSyncedPrefObserver(const std::string& name,
438                                                 SyncedPrefObserver* observer) {
439   auto& observers = synced_pref_observers_[name];
440   if (!observers)
441     observers = std::make_unique<SyncedPrefObserverList>();
442
443   observers->AddObserver(observer);
444 }
445
446 void PrefModelAssociator::RemoveSyncedPrefObserver(
447     const std::string& name,
448     SyncedPrefObserver* observer) {
449   auto observer_iter = synced_pref_observers_.find(name);
450   if (observer_iter == synced_pref_observers_.end())
451     return;
452   observer_iter->second->RemoveObserver(observer);
453 }
454
455 void PrefModelAssociator::RegisterPref(const std::string& name) {
456   DCHECK(!registered_preferences_.count(name));
457   registered_preferences_.insert(name);
458
459   // This pref might be registered after sync started. Make sure data in the
460   // local store matches the registered type.
461   // If this results in a modification of the local pref store, we don't want
462   // to tell ChromeSync about these -- it's a local anomaly,
463   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
464   pref_accessor_->EnforceRegisteredTypeInStore(name);
465 }
466
467 bool PrefModelAssociator::IsPrefRegistered(const std::string& name) const {
468   return registered_preferences_.count(name) > 0;
469 }
470
471 void PrefModelAssociator::ProcessPrefChange(const std::string& name) {
472   if (processing_syncer_changes_)
473     return;  // These are changes originating from us, ignore.
474
475   // We only process changes if we've already associated models.
476   // This also filters out local changes during the initial merge.
477   if (!models_associated_)
478     return;
479
480   // From now on, this method does not have to deal with lazily registered
481   // prefs, as local changes can only happen after they were registered.
482
483   const PrefService::Preference* preference =
484       pref_service_->FindPreference(name);
485   // TODO(tschumann): When can this ever happen? Should this be a DCHECK?
486   if (!preference)
487     return;
488
489   if (!IsPrefRegistered(name)) {
490     // We are not syncing this preference -- this also filters out synced
491     // preferences of the wrong type (priority preference are handled by a
492     // separate associator).
493     return;
494   }
495
496   syncer::SyncChangeList changes;
497
498   if (!preference->IsUserModifiable()) {
499     // If the preference is no longer user modifiable, it must now be
500     // controlled by policy, whose values we do not sync. Just return. If the
501     // preference stops being controlled by policy, it will revert back to the
502     // user value (which we continue to update with sync changes).
503     return;
504   }
505
506   base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
507
508   NotifySyncedPrefObservers(name, false /*from_sync*/);
509
510   if (synced_preferences_.count(name) == 0) {
511     // Not in synced_preferences_ means no synced data.
512     // InitPrefAndAssociate(..) will determine if we care about its data (e.g.
513     // if it has a default value and hasn't been changed yet we don't) and
514     // take care syncing any new data.
515     InitPrefAndAssociate(syncer::SyncData(), name, &changes);
516   } else {
517     // We are already syncing this preference, just update it's sync node.
518     syncer::SyncData sync_data;
519     if (!CreatePrefSyncData(name, *preference->GetValue(), &sync_data)) {
520       LOG(ERROR) << "Failed to update preference.";
521       return;
522     }
523     changes.push_back(syncer::SyncChange(
524         FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
525   }
526
527   syncer::SyncError error =
528       sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
529 }
530
531 void PrefModelAssociator::SetPrefService(PrefServiceSyncable* pref_service) {
532   DCHECK(pref_service_ == nullptr);
533   pref_service_ = pref_service;
534 }
535
536 void PrefModelAssociator::NotifySyncedPrefObservers(const std::string& path,
537                                                     bool from_sync) const {
538   auto observer_iter = synced_pref_observers_.find(path);
539   if (observer_iter == synced_pref_observers_.end())
540     return;
541   for (auto& observer : *observer_iter->second)
542     observer.OnSyncedPrefChanged(path, from_sync);
543 }
544
545 }  // namespace sync_preferences