Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / supervised_user / supervised_user_sync_service.cc
blob68e4d036f26c63dafe32a9b245e9a11b6982c8ff
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/supervised_user/supervised_user_sync_service.h"
7 #include <set>
9 #include "base/bind.h"
10 #include "base/callback.h"
11 #include "base/prefs/scoped_user_pref_update.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/stringprintf.h"
14 #include "base/values.h"
15 #include "chrome/browser/profiles/profile_avatar_icon_util.h"
16 #include "chrome/common/pref_names.h"
17 #include "components/pref_registry/pref_registry_syncable.h"
18 #include "sync/api/sync_change.h"
19 #include "sync/api/sync_data.h"
20 #include "sync/api/sync_error.h"
21 #include "sync/api/sync_error_factory.h"
22 #include "sync/api/sync_merge_result.h"
23 #include "sync/protocol/sync.pb.h"
25 #if defined(OS_CHROMEOS)
26 #include "components/user_manager/user_image/default_user_images.h"
27 #endif
29 using base::DictionaryValue;
30 using user_prefs::PrefRegistrySyncable;
31 using syncer::SUPERVISED_USERS;
32 using syncer::ModelType;
33 using syncer::SyncChange;
34 using syncer::SyncChangeList;
35 using syncer::SyncChangeProcessor;
36 using syncer::SyncData;
37 using syncer::SyncDataList;
38 using syncer::SyncError;
39 using syncer::SyncErrorFactory;
40 using syncer::SyncMergeResult;
41 using sync_pb::ManagedUserSpecifics;
43 namespace {
45 #if defined(OS_CHROMEOS)
46 const char kChromeOSAvatarPrefix[] = "chromeos-avatar-index:";
47 #else
48 const char kChromeAvatarPrefix[] = "chrome-avatar-index:";
49 #endif
51 SyncData CreateLocalSyncData(const std::string& id,
52 const std::string& name,
53 bool acknowledged,
54 const std::string& master_key,
55 const std::string& chrome_avatar,
56 const std::string& chromeos_avatar,
57 const std::string& password_signature_key,
58 const std::string& password_encryption_key) {
59 ::sync_pb::EntitySpecifics specifics;
60 specifics.mutable_managed_user()->set_id(id);
61 specifics.mutable_managed_user()->set_name(name);
62 if (!chrome_avatar.empty())
63 specifics.mutable_managed_user()->set_chrome_avatar(chrome_avatar);
64 if (!chromeos_avatar.empty())
65 specifics.mutable_managed_user()->set_chromeos_avatar(chromeos_avatar);
66 if (!master_key.empty())
67 specifics.mutable_managed_user()->set_master_key(master_key);
68 if (acknowledged)
69 specifics.mutable_managed_user()->set_acknowledged(true);
70 if (!password_signature_key.empty()) {
71 specifics.mutable_managed_user()->
72 set_password_signature_key(password_signature_key);
74 if (!password_encryption_key.empty()) {
75 specifics.mutable_managed_user()->
76 set_password_encryption_key(password_encryption_key);
78 return SyncData::CreateLocalData(id, name, specifics);
81 SyncData CreateSyncDataFromDictionaryEntry(const std::string& id,
82 const base::Value& value) {
83 const base::DictionaryValue* dict = NULL;
84 bool success = value.GetAsDictionary(&dict);
85 DCHECK(success);
86 bool acknowledged = false;
87 dict->GetBoolean(SupervisedUserSyncService::kAcknowledged, &acknowledged);
88 std::string name;
89 dict->GetString(SupervisedUserSyncService::kName, &name);
90 DCHECK(!name.empty());
91 std::string master_key;
92 dict->GetString(SupervisedUserSyncService::kMasterKey, &master_key);
93 std::string chrome_avatar;
94 dict->GetString(SupervisedUserSyncService::kChromeAvatar, &chrome_avatar);
95 std::string chromeos_avatar;
96 dict->GetString(SupervisedUserSyncService::kChromeOsAvatar, &chromeos_avatar);
97 std::string signature;
98 dict->GetString(SupervisedUserSyncService::kPasswordSignatureKey, &signature);
99 std::string encryption;
100 dict->GetString(SupervisedUserSyncService::kPasswordEncryptionKey,
101 &encryption);
103 return CreateLocalSyncData(id,
104 name,
105 acknowledged,
106 master_key,
107 chrome_avatar,
108 chromeos_avatar,
109 signature,
110 encryption);
113 } // namespace
115 const char SupervisedUserSyncService::kAcknowledged[] = "acknowledged";
116 const char SupervisedUserSyncService::kChromeAvatar[] = "chromeAvatar";
117 const char SupervisedUserSyncService::kChromeOsAvatar[] = "chromeOsAvatar";
118 const char SupervisedUserSyncService::kMasterKey[] = "masterKey";
119 const char SupervisedUserSyncService::kName[] = "name";
120 const char SupervisedUserSyncService::kPasswordSignatureKey[] =
121 "passwordSignatureKey";
122 const char SupervisedUserSyncService::kPasswordEncryptionKey[] =
123 "passwordEncryptionKey";
124 const int SupervisedUserSyncService::kNoAvatar = -100;
126 SupervisedUserSyncService::SupervisedUserSyncService(PrefService* prefs)
127 : prefs_(prefs) {
128 pref_change_registrar_.Init(prefs_);
129 pref_change_registrar_.Add(
130 prefs::kGoogleServicesLastUsername,
131 base::Bind(&SupervisedUserSyncService::OnLastSignedInUsernameChange,
132 base::Unretained(this)));
135 SupervisedUserSyncService::~SupervisedUserSyncService() {
138 // static
139 void SupervisedUserSyncService::RegisterProfilePrefs(
140 PrefRegistrySyncable* registry) {
141 registry->RegisterDictionaryPref(prefs::kSupervisedUsers,
142 PrefRegistrySyncable::UNSYNCABLE_PREF);
145 // static
146 bool SupervisedUserSyncService::GetAvatarIndex(const std::string& avatar_str,
147 int* avatar_index) {
148 DCHECK(avatar_index);
149 if (avatar_str.empty()) {
150 *avatar_index = kNoAvatar;
151 return true;
153 #if defined(OS_CHROMEOS)
154 const char* prefix = kChromeOSAvatarPrefix;
155 #else
156 const char* prefix = kChromeAvatarPrefix;
157 #endif
158 size_t prefix_len = strlen(prefix);
159 if (avatar_str.size() <= prefix_len ||
160 avatar_str.substr(0, prefix_len) != prefix) {
161 return false;
164 if (!base::StringToInt(avatar_str.substr(prefix_len), avatar_index))
165 return false;
167 const int kChromeOSDummyAvatarIndex = -111;
169 #if defined(OS_CHROMEOS)
170 return (*avatar_index == kChromeOSDummyAvatarIndex ||
171 (*avatar_index >= user_manager::kFirstDefaultImageIndex &&
172 *avatar_index < user_manager::kDefaultImagesCount));
173 #else
174 // Check if the Chrome avatar index is set to a dummy value. Some early
175 // supervised user profiles on ChromeOS stored a dummy avatar index as a
176 // Chrome Avatar before there was logic to sync the ChromeOS avatar
177 // separately. Handle this as if the Chrome Avatar was not chosen yet (which
178 // is correct for these profiles).
179 if (*avatar_index == kChromeOSDummyAvatarIndex)
180 *avatar_index = kNoAvatar;
181 return (*avatar_index == kNoAvatar ||
182 (*avatar_index >= 0 &&
183 static_cast<size_t>(*avatar_index) <
184 profiles::GetDefaultAvatarIconCount()));
185 #endif
188 // static
189 std::string SupervisedUserSyncService::BuildAvatarString(int avatar_index) {
190 #if defined(OS_CHROMEOS)
191 const char* prefix = kChromeOSAvatarPrefix;
192 #else
193 const char* prefix = kChromeAvatarPrefix;
194 #endif
195 return base::StringPrintf("%s%d", prefix, avatar_index);
198 void SupervisedUserSyncService::AddObserver(
199 SupervisedUserSyncServiceObserver* observer) {
200 observers_.AddObserver(observer);
203 void SupervisedUserSyncService::RemoveObserver(
204 SupervisedUserSyncServiceObserver* observer) {
205 observers_.RemoveObserver(observer);
208 scoped_ptr<base::DictionaryValue> SupervisedUserSyncService::CreateDictionary(
209 const std::string& name,
210 const std::string& master_key,
211 const std::string& signature_key,
212 const std::string& encryption_key,
213 int avatar_index) {
214 scoped_ptr<base::DictionaryValue> result(new base::DictionaryValue());
215 result->SetString(kName, name);
216 result->SetString(kMasterKey, master_key);
217 result->SetString(kPasswordSignatureKey, signature_key);
218 result->SetString(kPasswordEncryptionKey, encryption_key);
219 // TODO(akuegel): Get rid of the avatar stuff here when Chrome OS switches
220 // to the avatar index that is stored as a shared setting.
221 std::string chrome_avatar;
222 std::string chromeos_avatar;
223 #if defined(OS_CHROMEOS)
224 chromeos_avatar = BuildAvatarString(avatar_index);
225 #else
226 chrome_avatar = BuildAvatarString(avatar_index);
227 #endif
228 result->SetString(kChromeAvatar, chrome_avatar);
229 result->SetString(kChromeOsAvatar, chromeos_avatar);
230 return result.Pass();
233 void SupervisedUserSyncService::AddSupervisedUser(
234 const std::string& id,
235 const std::string& name,
236 const std::string& master_key,
237 const std::string& signature_key,
238 const std::string& encryption_key,
239 int avatar_index) {
240 UpdateSupervisedUserImpl(id,
241 name,
242 master_key,
243 signature_key,
244 encryption_key,
245 avatar_index,
246 true /* add */);
249 void SupervisedUserSyncService::UpdateSupervisedUser(
250 const std::string& id,
251 const std::string& name,
252 const std::string& master_key,
253 const std::string& signature_key,
254 const std::string& encryption_key,
255 int avatar_index) {
256 UpdateSupervisedUserImpl(id,
257 name,
258 master_key,
259 signature_key,
260 encryption_key,
261 avatar_index,
262 false /* update */);
265 void SupervisedUserSyncService::UpdateSupervisedUserImpl(
266 const std::string& id,
267 const std::string& name,
268 const std::string& master_key,
269 const std::string& signature_key,
270 const std::string& encryption_key,
271 int avatar_index,
272 bool add_user) {
273 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
274 base::DictionaryValue* dict = update.Get();
275 scoped_ptr<base::DictionaryValue> value = CreateDictionary(
276 name, master_key, signature_key, encryption_key, avatar_index);
278 DCHECK_EQ(add_user, !dict->HasKey(id));
279 base::DictionaryValue* entry = value.get();
280 dict->SetWithoutPathExpansion(id, value.release());
282 if (!sync_processor_)
283 return;
285 // If we're already syncing, create a new change and upload it.
286 SyncChangeList change_list;
287 change_list.push_back(
288 SyncChange(FROM_HERE,
289 add_user ? SyncChange::ACTION_ADD : SyncChange::ACTION_UPDATE,
290 CreateSyncDataFromDictionaryEntry(id, *entry)));
291 SyncError error =
292 sync_processor_->ProcessSyncChanges(FROM_HERE, change_list);
293 DCHECK(!error.IsSet()) << error.ToString();
296 void SupervisedUserSyncService::DeleteSupervisedUser(const std::string& id) {
297 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
298 bool success = update->RemoveWithoutPathExpansion(id, NULL);
299 DCHECK(success);
301 if (!sync_processor_)
302 return;
304 SyncChangeList change_list;
305 change_list.push_back(SyncChange(
306 FROM_HERE,
307 SyncChange::ACTION_DELETE,
308 SyncData::CreateLocalDelete(id, SUPERVISED_USERS)));
309 SyncError sync_error =
310 sync_processor_->ProcessSyncChanges(FROM_HERE, change_list);
311 DCHECK(!sync_error.IsSet());
314 const base::DictionaryValue* SupervisedUserSyncService::GetSupervisedUsers() {
315 DCHECK(sync_processor_);
316 return prefs_->GetDictionary(prefs::kSupervisedUsers);
319 bool SupervisedUserSyncService::UpdateSupervisedUserAvatarIfNeeded(
320 const std::string& id,
321 int avatar_index) {
322 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
323 base::DictionaryValue* dict = update.Get();
324 DCHECK(dict->HasKey(id));
325 base::DictionaryValue* value = NULL;
326 bool success = dict->GetDictionaryWithoutPathExpansion(id, &value);
327 DCHECK(success);
329 bool acknowledged = false;
330 value->GetBoolean(SupervisedUserSyncService::kAcknowledged, &acknowledged);
331 std::string name;
332 value->GetString(SupervisedUserSyncService::kName, &name);
333 std::string master_key;
334 value->GetString(SupervisedUserSyncService::kMasterKey, &master_key);
335 std::string signature;
336 value->GetString(SupervisedUserSyncService::kPasswordSignatureKey,
337 &signature);
338 std::string encryption;
339 value->GetString(SupervisedUserSyncService::kPasswordEncryptionKey,
340 &encryption);
341 std::string chromeos_avatar;
342 value->GetString(SupervisedUserSyncService::kChromeOsAvatar,
343 &chromeos_avatar);
344 std::string chrome_avatar;
345 value->GetString(SupervisedUserSyncService::kChromeAvatar, &chrome_avatar);
346 // The following check is just for safety. We want to avoid that the existing
347 // avatar selection is overwritten. Currently we don't allow the user to
348 // choose a different avatar in the recreation dialog, anyway, if there is
349 // already an avatar selected.
350 #if defined(OS_CHROMEOS)
351 if (!chromeos_avatar.empty() && avatar_index != kNoAvatar)
352 return false;
353 #else
354 if (!chrome_avatar.empty() && avatar_index != kNoAvatar)
355 return false;
356 #endif
358 chrome_avatar = avatar_index == kNoAvatar ?
359 std::string() : BuildAvatarString(avatar_index);
360 #if defined(OS_CHROMEOS)
361 value->SetString(kChromeOsAvatar, chrome_avatar);
362 #else
363 value->SetString(kChromeAvatar, chrome_avatar);
364 #endif
366 if (!sync_processor_)
367 return true;
369 SyncChangeList change_list;
370 change_list.push_back(SyncChange(
371 FROM_HERE,
372 SyncChange::ACTION_UPDATE,
373 CreateLocalSyncData(id, name, acknowledged, master_key,
374 chrome_avatar, chromeos_avatar,
375 signature, encryption)));
376 SyncError error =
377 sync_processor_->ProcessSyncChanges(FROM_HERE, change_list);
378 DCHECK(!error.IsSet()) << error.ToString();
379 return true;
382 void SupervisedUserSyncService::ClearSupervisedUserAvatar(
383 const std::string& id) {
384 bool cleared = UpdateSupervisedUserAvatarIfNeeded(id, kNoAvatar);
385 DCHECK(cleared);
388 void SupervisedUserSyncService::GetSupervisedUsersAsync(
389 const SupervisedUsersCallback& callback) {
390 // If we are already syncing, just run the callback.
391 if (sync_processor_) {
392 callback.Run(GetSupervisedUsers());
393 return;
396 // Otherwise queue it up until we start syncing.
397 callbacks_.push_back(callback);
400 void SupervisedUserSyncService::Shutdown() {
401 NotifySupervisedUsersSyncingStopped();
404 SyncMergeResult SupervisedUserSyncService::MergeDataAndStartSyncing(
405 ModelType type,
406 const SyncDataList& initial_sync_data,
407 scoped_ptr<SyncChangeProcessor> sync_processor,
408 scoped_ptr<SyncErrorFactory> error_handler) {
409 DCHECK_EQ(SUPERVISED_USERS, type);
410 sync_processor_ = sync_processor.Pass();
411 error_handler_ = error_handler.Pass();
413 SyncChangeList change_list;
414 SyncMergeResult result(SUPERVISED_USERS);
416 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
417 base::DictionaryValue* dict = update.Get();
418 result.set_num_items_before_association(dict->size());
419 std::set<std::string> seen_ids;
420 int num_items_added = 0;
421 int num_items_modified = 0;
422 for (const SyncData& sync_data : initial_sync_data) {
423 DCHECK_EQ(SUPERVISED_USERS, sync_data.GetDataType());
424 const ManagedUserSpecifics& supervised_user =
425 sync_data.GetSpecifics().managed_user();
426 base::DictionaryValue* value = new base::DictionaryValue();
427 value->SetString(kName, supervised_user.name());
428 value->SetBoolean(kAcknowledged, supervised_user.acknowledged());
429 value->SetString(kMasterKey, supervised_user.master_key());
430 value->SetString(kChromeAvatar, supervised_user.chrome_avatar());
431 value->SetString(kChromeOsAvatar, supervised_user.chromeos_avatar());
432 value->SetString(kPasswordSignatureKey,
433 supervised_user.password_signature_key());
434 value->SetString(kPasswordEncryptionKey,
435 supervised_user.password_encryption_key());
436 if (dict->HasKey(supervised_user.id()))
437 num_items_modified++;
438 else
439 num_items_added++;
440 dict->SetWithoutPathExpansion(supervised_user.id(), value);
441 seen_ids.insert(supervised_user.id());
444 for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance()) {
445 if (seen_ids.find(it.key()) != seen_ids.end())
446 continue;
448 change_list.push_back(
449 SyncChange(FROM_HERE,
450 SyncChange::ACTION_ADD,
451 CreateSyncDataFromDictionaryEntry(it.key(), it.value())));
453 result.set_error(sync_processor_->ProcessSyncChanges(FROM_HERE, change_list));
455 result.set_num_items_modified(num_items_modified);
456 result.set_num_items_added(num_items_added);
457 result.set_num_items_after_association(dict->size());
459 DispatchCallbacks();
461 return result;
464 void SupervisedUserSyncService::StopSyncing(ModelType type) {
465 DCHECK_EQ(SUPERVISED_USERS, type);
466 // The observers may want to change the Sync data, so notify them before
467 // resetting the |sync_processor_|.
468 NotifySupervisedUsersSyncingStopped();
469 sync_processor_.reset();
470 error_handler_.reset();
473 SyncDataList SupervisedUserSyncService::GetAllSyncData(
474 ModelType type) const {
475 SyncDataList data;
476 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
477 base::DictionaryValue* dict = update.Get();
478 for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd(); it.Advance())
479 data.push_back(CreateSyncDataFromDictionaryEntry(it.key(), it.value()));
481 return data;
484 SyncError SupervisedUserSyncService::ProcessSyncChanges(
485 const tracked_objects::Location& from_here,
486 const SyncChangeList& change_list) {
487 SyncError error;
488 DictionaryPrefUpdate update(prefs_, prefs::kSupervisedUsers);
489 base::DictionaryValue* dict = update.Get();
490 for (const SyncChange& sync_change : change_list) {
491 SyncData data = sync_change.sync_data();
492 DCHECK_EQ(SUPERVISED_USERS, data.GetDataType());
493 const ManagedUserSpecifics& supervised_user =
494 data.GetSpecifics().managed_user();
495 switch (sync_change.change_type()) {
496 case SyncChange::ACTION_ADD:
497 case SyncChange::ACTION_UPDATE: {
498 // Every item we get from the server should be acknowledged.
499 DCHECK(supervised_user.acknowledged());
500 const base::DictionaryValue* old_value = NULL;
501 dict->GetDictionaryWithoutPathExpansion(supervised_user.id(),
502 &old_value);
504 // For an update action, the supervised user should already exist, for
505 // an add action, it should not.
506 DCHECK_EQ(
507 old_value ? SyncChange::ACTION_UPDATE : SyncChange::ACTION_ADD,
508 sync_change.change_type());
510 // If the supervised user switched from unacknowledged to acknowledged,
511 // we might need to continue with a registration.
512 if (old_value && !old_value->HasKey(kAcknowledged))
513 NotifySupervisedUserAcknowledged(supervised_user.id());
515 base::DictionaryValue* value = new base::DictionaryValue;
516 value->SetString(kName, supervised_user.name());
517 value->SetBoolean(kAcknowledged, supervised_user.acknowledged());
518 value->SetString(kMasterKey, supervised_user.master_key());
519 value->SetString(kChromeAvatar, supervised_user.chrome_avatar());
520 value->SetString(kChromeOsAvatar, supervised_user.chromeos_avatar());
521 value->SetString(kPasswordSignatureKey,
522 supervised_user.password_signature_key());
523 value->SetString(kPasswordEncryptionKey,
524 supervised_user.password_encryption_key());
525 dict->SetWithoutPathExpansion(supervised_user.id(), value);
527 NotifySupervisedUsersChanged();
528 break;
530 case SyncChange::ACTION_DELETE: {
531 DCHECK(dict->HasKey(supervised_user.id())) << supervised_user.id();
532 dict->RemoveWithoutPathExpansion(supervised_user.id(), NULL);
533 break;
535 case SyncChange::ACTION_INVALID: {
536 NOTREACHED();
537 break;
541 return error;
544 void SupervisedUserSyncService::OnLastSignedInUsernameChange() {
545 DCHECK(!sync_processor_);
547 // If the last signed in user changes, we clear all data, to avoid supervised
548 // users from one custodian appearing in another one's profile.
549 prefs_->ClearPref(prefs::kSupervisedUsers);
552 void SupervisedUserSyncService::NotifySupervisedUserAcknowledged(
553 const std::string& supervised_user_id) {
554 FOR_EACH_OBSERVER(SupervisedUserSyncServiceObserver, observers_,
555 OnSupervisedUserAcknowledged(supervised_user_id));
558 void SupervisedUserSyncService::NotifySupervisedUsersSyncingStopped() {
559 FOR_EACH_OBSERVER(SupervisedUserSyncServiceObserver, observers_,
560 OnSupervisedUsersSyncingStopped());
563 void SupervisedUserSyncService::NotifySupervisedUsersChanged() {
564 FOR_EACH_OBSERVER(SupervisedUserSyncServiceObserver,
565 observers_,
566 OnSupervisedUsersChanged());
569 void SupervisedUserSyncService::DispatchCallbacks() {
570 const base::DictionaryValue* supervised_users =
571 prefs_->GetDictionary(prefs::kSupervisedUsers);
572 for (const auto& callback : callbacks_)
573 callback.Run(supervised_users);
574 callbacks_.clear();