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.
5 #include "components/sync_preferences/pref_model_associator.h"
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"
33 using syncer::PREFERENCES;
34 using syncer::PRIORITY_PREFERENCES;
36 namespace sync_preferences {
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();
46 return pref.GetSpecifics().preference();
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();
57 DCHECK(!specifics->has_priority_preference());
58 return specifics->mutable_preference();
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);
73 PrefModelAssociator::~PrefModelAssociator() {
74 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
75 pref_service_ = nullptr;
77 synced_pref_observers_.clear();
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.
93 VLOG(1) << "Associating preference " << pref_name;
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();
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));
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);
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.";
131 sync_changes->push_back(syncer::SyncChange(
132 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
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);
138 LOG(WARNING) << "Sync has null value for pref " << pref_name.c_str();
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,
149 LOG(ERROR) << "Failed to update preference.";
152 sync_changes->push_back(syncer::SyncChange(
153 FROM_HERE, syncer::SyncChange::ACTION_ADD, sync_data));
154 synced_preferences_.insert(pref_name);
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.
163 void PrefModelAssociator::RegisterMergeDataFinishedCallback(
164 const base::Closure& callback) {
165 if (!models_associated_)
166 callback_list_.push_back(callback);
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);
186 syncer::SyncChangeList new_changes;
187 std::set<std::string> remaining_preferences = registered_preferences_;
189 // Go through and check for all preferences we care about that sync already
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());
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);
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);
207 UMA_HISTOGRAM_COUNTS_1000("Sync.Preferences.SyncingUnknownPrefs",
208 pref_accessor_->GetNumberOfSyncingUnknownPrefs());
210 // Push updates to sync.
211 merge_result.set_error(
212 sync_processor_->ProcessSyncChanges(FROM_HERE, new_changes));
213 if (merge_result.error().IsSet())
216 for (const auto& callback : callback_list_)
218 callback_list_.clear();
220 models_associated_ = true;
221 pref_service_->OnIsSyncingChanged();
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();
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.
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));
247 std::unique_ptr<base::Value> merged_value =
248 client_->MaybeMergePreferenceValues(name, local_value, server_value);
253 // If this is not a specially handled preference, server wins.
254 return base::WrapUnique(server_value.DeepCopy());
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;
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.";
275 sync_pb::EntitySpecifics specifics;
276 sync_pb::PreferenceSpecifics* pref_specifics =
277 GetMutableSpecifics(type_, &specifics);
279 pref_specifics->set_name(name);
280 pref_specifics->set_value(serialized);
281 *sync_data = syncer::SyncData::CreateLocalData(name, name, specifics);
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());
293 DCHECK(from_value.type() == base::Value::Type::LIST);
294 DCHECK(to_value.type() == base::Value::Type::LIST);
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());
303 return base::Value::ToUniquePtrValue(std::move(result));
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();
314 DCHECK(from_value.is_dict());
315 DCHECK(to_value.is_dict());
316 base::Value result = to_value.Clone();
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);
322 if (from_key_value->is_dict() && to_key_value->is_dict()) {
323 *to_key_value = MergeDictionaryValues(*from_key_value, *to_key_value);
325 // Note that for all other types we want to preserve the "to"
326 // values so we do nothing here.
328 result.SetKey(it.first, from_key_value->Clone());
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) {
345 const PrefService::Preference* pref = pref_service_->FindPreference(name);
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))
353 current_data.push_back(sync_data);
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);
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());
371 const sync_pb::PreferenceSpecifics& pref_specifics =
372 GetSpecifics(iter->sync_data());
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.
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.
390 if (iter->change_type() == syncer::SyncChange::ACTION_DELETE) {
391 pref_accessor_->ClearPref(pref_specifics.name(), local_pref_state);
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
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,
410 NotifySyncedPrefObservers(pref_specifics.name(), true /*from_sync*/);
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());
416 return syncer::SyncError();
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()));
426 "Failed to deserialize preference value: " + reader.GetErrorMessage();
430 return value.release();
433 bool PrefModelAssociator::IsPrefSynced(const std::string& name) const {
434 return synced_preferences_.find(name) != synced_preferences_.end();
437 void PrefModelAssociator::AddSyncedPrefObserver(const std::string& name,
438 SyncedPrefObserver* observer) {
439 auto& observers = synced_pref_observers_[name];
441 observers = std::make_unique<SyncedPrefObserverList>();
443 observers->AddObserver(observer);
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())
452 observer_iter->second->RemoveObserver(observer);
455 void PrefModelAssociator::RegisterPref(const std::string& name) {
456 DCHECK(!registered_preferences_.count(name));
457 registered_preferences_.insert(name);
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);
467 bool PrefModelAssociator::IsPrefRegistered(const std::string& name) const {
468 return registered_preferences_.count(name) > 0;
471 void PrefModelAssociator::ProcessPrefChange(const std::string& name) {
472 if (processing_syncer_changes_)
473 return; // These are changes originating from us, ignore.
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_)
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.
483 const PrefService::Preference* preference =
484 pref_service_->FindPreference(name);
485 // TODO(tschumann): When can this ever happen? Should this be a DCHECK?
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).
496 syncer::SyncChangeList changes;
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).
506 base::AutoReset<bool> processing_changes(&processing_syncer_changes_, true);
508 NotifySyncedPrefObservers(name, false /*from_sync*/);
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);
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.";
523 changes.push_back(syncer::SyncChange(
524 FROM_HERE, syncer::SyncChange::ACTION_UPDATE, sync_data));
527 syncer::SyncError error =
528 sync_processor_->ProcessSyncChanges(FROM_HERE, changes);
531 void PrefModelAssociator::SetPrefService(PrefServiceSyncable* pref_service) {
532 DCHECK(pref_service_ == nullptr);
533 pref_service_ = pref_service;
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())
541 for (auto& observer : *observer_iter->second)
542 observer.OnSyncedPrefChanged(path, from_sync);
545 } // namespace sync_preferences