Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blob7ea11bc436346c347ce2cec75874136c9a0a2ee3
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 "chrome/browser/sync/profile_sync_service.h"
7 #include <cstddef>
8 #include <map>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/metrics/histogram.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "build/build_config.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/browsing_data/browsing_data_helper.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/defaults.h"
31 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
32 #include "chrome/browser/net/chrome_cookie_notification_details.h"
33 #include "chrome/browser/password_manager/password_store_factory.h"
34 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
35 #include "chrome/browser/prefs/pref_service_syncable.h"
36 #include "chrome/browser/profiles/profile.h"
37 #include "chrome/browser/signin/about_signin_internals_factory.h"
38 #include "chrome/browser/signin/chrome_signin_client_factory.h"
39 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
40 #include "chrome/browser/signin/signin_manager_factory.h"
41 #include "chrome/browser/sync/backend_migrator.h"
42 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
43 #include "chrome/browser/sync/glue/favicon_cache.h"
44 #include "chrome/browser/sync/glue/sync_backend_host.h"
45 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
46 #include "chrome/browser/sync/glue/sync_start_util.h"
47 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
48 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
49 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
50 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
51 #include "chrome/browser/sync/sync_error_controller.h"
52 #include "chrome/browser/sync/sync_stopped_reporter.h"
53 #include "chrome/browser/sync/sync_type_preference_provider.h"
54 #include "chrome/browser/ui/browser.h"
55 #include "chrome/browser/ui/browser_list.h"
56 #include "chrome/browser/ui/browser_window.h"
57 #include "chrome/browser/ui/global_error/global_error_service.h"
58 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
59 #include "chrome/common/chrome_switches.h"
60 #include "chrome/common/chrome_version_info.h"
61 #include "chrome/common/pref_names.h"
62 #include "chrome/common/url_constants.h"
63 #include "chrome/grit/generated_resources.h"
64 #include "components/autofill/core/common/autofill_pref_names.h"
65 #include "components/invalidation/invalidation_service.h"
66 #include "components/invalidation/profile_invalidation_provider.h"
67 #include "components/password_manager/core/browser/password_store.h"
68 #include "components/pref_registry/pref_registry_syncable.h"
69 #include "components/signin/core/browser/about_signin_internals.h"
70 #include "components/signin/core/browser/profile_oauth2_token_service.h"
71 #include "components/signin/core/browser/signin_manager.h"
72 #include "components/signin/core/browser/signin_metrics.h"
73 #include "components/sync_driver/change_processor.h"
74 #include "components/sync_driver/data_type_controller.h"
75 #include "components/sync_driver/device_info.h"
76 #include "components/sync_driver/pref_names.h"
77 #include "components/sync_driver/system_encryptor.h"
78 #include "components/sync_driver/user_selectable_sync_type.h"
79 #include "content/public/browser/browser_thread.h"
80 #include "content/public/browser/notification_details.h"
81 #include "content/public/browser/notification_service.h"
82 #include "content/public/browser/notification_source.h"
83 #include "net/cookies/cookie_monster.h"
84 #include "net/url_request/url_request_context_getter.h"
85 #include "sync/api/sync_error.h"
86 #include "sync/internal_api/public/configure_reason.h"
87 #include "sync/internal_api/public/http_bridge_network_resources.h"
88 #include "sync/internal_api/public/network_resources.h"
89 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
90 #include "sync/internal_api/public/shutdown_reason.h"
91 #include "sync/internal_api/public/sync_context_proxy.h"
92 #include "sync/internal_api/public/sync_encryption_handler.h"
93 #include "sync/internal_api/public/util/experiments.h"
94 #include "sync/internal_api/public/util/sync_db_util.h"
95 #include "sync/internal_api/public/util/sync_string_conversions.h"
96 #include "sync/js/js_event_details.h"
97 #include "sync/protocol/sync.pb.h"
98 #include "sync/syncable/directory.h"
99 #include "sync/util/cryptographer.h"
100 #include "ui/base/l10n/l10n_util.h"
101 #include "ui/base/l10n/time_format.h"
103 #if defined(OS_ANDROID)
104 #include "sync/internal_api/public/read_transaction.h"
105 #endif
107 using browser_sync::NotificationServiceSessionsRouter;
108 using browser_sync::ProfileSyncServiceStartBehavior;
109 using browser_sync::SessionsSyncManager;
110 using browser_sync::SyncBackendHost;
111 using sync_driver::ChangeProcessor;
112 using sync_driver::DataTypeController;
113 using sync_driver::DataTypeManager;
114 using sync_driver::DataTypeStatusTable;
115 using sync_driver::DeviceInfoSyncService;
116 using syncer::ModelType;
117 using syncer::ModelTypeSet;
118 using syncer::JsBackend;
119 using syncer::JsController;
120 using syncer::JsEventDetails;
121 using syncer::JsEventHandler;
122 using syncer::ModelSafeRoutingInfo;
123 using syncer::SyncCredentials;
124 using syncer::SyncProtocolError;
125 using syncer::WeakHandle;
127 typedef GoogleServiceAuthError AuthError;
129 const char* ProfileSyncService::kSyncServerUrl =
130 "https://clients4.google.com/chrome-sync";
132 const char* ProfileSyncService::kDevServerUrl =
133 "https://clients4.google.com/chrome-sync/dev";
135 const char kSyncUnrecoverableErrorHistogram[] =
136 "Sync.UnrecoverableErrors";
138 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
139 // Number of initial errors (in sequence) to ignore before applying
140 // exponential back-off rules.
143 // Initial delay for exponential back-off in ms.
144 2000,
146 // Factor by which the waiting time will be multiplied.
149 // Fuzzing percentage. ex: 10% will spread requests randomly
150 // between 90%-100% of the calculated time.
151 0.2, // 20%
153 // Maximum amount of time we are willing to delay our request in ms.
154 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
155 // RequestAccessToken on connection state change after backoff
156 1000 * 3600 * 4, // 4 hours.
158 // Time to keep an entry from being discarded even when it
159 // has no significant state, -1 to never discard.
162 // Don't use initial delay unless the last request was an error.
163 false,
166 static const base::FilePath::CharType kSyncDataFolderName[] =
167 FILE_PATH_LITERAL("Sync Data");
169 static const base::FilePath::CharType kSyncBackupDataFolderName[] =
170 FILE_PATH_LITERAL("Sync Data Backup");
172 namespace {
174 void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
175 Profile* profile,
176 base::Time start,
177 base::Time end) {
178 // BrowsingDataRemover deletes itself when it's done.
179 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
180 profile, start, end);
181 if (observer)
182 remover->AddObserver(observer);
183 remover->Remove(BrowsingDataRemover::REMOVE_ALL,
184 BrowsingDataHelper::ALL);
186 scoped_refptr<password_manager::PasswordStore> password =
187 PasswordStoreFactory::GetForProfile(profile,
188 ServiceAccessType::EXPLICIT_ACCESS);
189 password->RemoveLoginsSyncedBetween(start, end);
192 // Perform the actual sync data folder deletion.
193 // This should only be called on the sync thread.
194 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
195 if (base::DirectoryExists(directory_path)) {
196 if (!base::DeleteFile(directory_path, true))
197 LOG(DFATAL) << "Could not delete the Sync Data folder.";
201 } // anonymous namespace
203 bool ShouldShowActionOnUI(
204 const syncer::SyncProtocolError& error) {
205 return (error.action != syncer::UNKNOWN_ACTION &&
206 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
207 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
210 ProfileSyncService::ProfileSyncService(
211 scoped_ptr<ProfileSyncComponentsFactory> factory,
212 Profile* profile,
213 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
214 ProfileOAuth2TokenService* oauth2_token_service,
215 ProfileSyncServiceStartBehavior start_behavior)
216 : OAuth2TokenService::Consumer("sync"),
217 last_auth_error_(AuthError::AuthErrorNone()),
218 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
219 factory_(factory.Pass()),
220 profile_(profile),
221 sync_prefs_(profile_->GetPrefs()),
222 sync_service_url_(
223 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
224 is_first_time_sync_configure_(false),
225 backend_initialized_(false),
226 sync_disabled_by_admin_(false),
227 is_auth_in_progress_(false),
228 signin_(signin_wrapper.Pass()),
229 unrecoverable_error_reason_(ERROR_REASON_UNSET),
230 expect_sync_configuration_aborted_(false),
231 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
232 encrypt_everything_allowed_(true),
233 encrypt_everything_(false),
234 encryption_pending_(false),
235 configure_status_(DataTypeManager::UNKNOWN),
236 oauth2_token_service_(oauth2_token_service),
237 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
238 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
239 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
240 network_resources_(new syncer::HttpBridgeNetworkResources),
241 backend_mode_(IDLE),
242 need_backup_(false),
243 backup_finished_(false),
244 clear_browsing_data_(base::Bind(&ClearBrowsingData)),
245 browsing_data_remover_observer_(NULL),
246 sync_stopped_reporter_(
247 new browser_sync::SyncStoppedReporter(
248 sync_service_url_,
249 profile_->GetRequestContext(),
250 browser_sync::SyncStoppedReporter::ResultCallback())),
251 weak_factory_(this),
252 startup_controller_weak_factory_(this) {
253 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
254 DCHECK(profile);
255 startup_controller_.reset(new browser_sync::StartupController(
256 start_behavior,
257 oauth2_token_service,
258 &sync_prefs_,
259 signin_.get(),
260 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
261 startup_controller_weak_factory_.GetWeakPtr(),
262 SYNC)));
263 backup_rollback_controller_.reset(new browser_sync::BackupRollbackController(
264 &sync_prefs_,
265 signin_.get(),
266 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
267 startup_controller_weak_factory_.GetWeakPtr(),
268 BACKUP),
269 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
270 startup_controller_weak_factory_.GetWeakPtr(),
271 ROLLBACK)));
272 syncer::SyncableService::StartSyncFlare flare(
273 sync_start_util::GetFlareForSyncableService(profile->GetPath()));
274 scoped_ptr<browser_sync::LocalSessionEventRouter> router(
275 new NotificationServiceSessionsRouter(profile, flare));
277 DCHECK(factory_.get());
278 local_device_ = factory_->CreateLocalDeviceInfoProvider();
279 sessions_sync_manager_.reset(
280 new SessionsSyncManager(profile, local_device_.get(), router.Pass()));
281 device_info_sync_service_.reset(
282 new DeviceInfoSyncService(local_device_.get()));
285 ProfileSyncService::~ProfileSyncService() {
286 sync_prefs_.RemoveSyncPrefObserver(this);
287 // Shutdown() should have been called before destruction.
288 CHECK(!backend_initialized_);
291 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
292 // Exit if sync is disabled.
293 if (IsManaged() || sync_prefs_.IsStartSuppressed())
294 return false;
296 // Sync is logged in if there is a non-empty effective username.
297 return !signin_->GetEffectiveUsername().empty();
300 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
301 if (!oauth2_token_service_)
302 return false;
304 return oauth2_token_service_->RefreshTokenIsAvailable(
305 signin_->GetAccountIdToUse());
308 void ProfileSyncService::Initialize() {
309 // We clear this here (vs Shutdown) because we want to remember that an error
310 // happened on shutdown so we can display details (message, location) about it
311 // in about:sync.
312 ClearStaleErrors();
314 sync_prefs_.AddSyncPrefObserver(this);
316 // For now, the only thing we can do through policy is to turn sync off.
317 if (IsManaged()) {
318 DisableForUser();
319 return;
322 RegisterAuthNotifications();
324 if (!HasSyncSetupCompleted() || signin_->GetEffectiveUsername().empty()) {
325 // Clean up in case of previous crash / setup abort / signout.
326 DisableForUser();
329 TrySyncDatatypePrefRecovery();
331 #if defined(OS_CHROMEOS)
332 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
333 if (bootstrap_token.empty()) {
334 sync_prefs_.SetEncryptionBootstrapToken(
335 sync_prefs_.GetSpareBootstrapToken());
337 #endif
339 #if !defined(OS_ANDROID)
340 DCHECK(sync_error_controller_ == NULL)
341 << "Initialize() called more than once.";
342 sync_error_controller_.reset(new SyncErrorController(this));
343 AddObserver(sync_error_controller_.get());
344 #endif
346 bool running_rollback = false;
347 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
348 // Backup is needed if user's not signed in or signed in but previous
349 // backup didn't finish, i.e. backend didn't switch from backup to sync.
350 need_backup_ = signin_->GetEffectiveUsername().empty() ||
351 sync_prefs_.GetFirstSyncTime().is_null();
353 // Try to resume rollback if it didn't finish in last session.
354 running_rollback = backup_rollback_controller_->StartRollback();
355 } else {
356 need_backup_ = false;
359 #if defined(ENABLE_PRE_SYNC_BACKUP)
360 if (!running_rollback && signin_->GetEffectiveUsername().empty()) {
361 CleanUpBackup();
363 #else
364 DCHECK(!running_rollback);
365 #endif
367 startup_controller_->Reset(GetRegisteredDataTypes());
368 startup_controller_->TryStart();
371 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
372 DCHECK(!backend_initialized());
373 if (!HasSyncSetupCompleted())
374 return;
376 // There was a bug where OnUserChoseDatatypes was not properly called on
377 // configuration (see crbug.com/154940). We detect this by checking whether
378 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
379 // completed, it means sync was not properly configured, so we manually
380 // set kSyncKeepEverythingSynced.
381 PrefService* const pref_service = profile_->GetPrefs();
382 if (!pref_service)
383 return;
384 if (GetPreferredDataTypes().Size() > 1)
385 return;
387 const PrefService::Preference* keep_everything_synced =
388 pref_service->FindPreference(
389 sync_driver::prefs::kSyncKeepEverythingSynced);
390 // This will be false if the preference was properly set or if it's controlled
391 // by policy.
392 if (!keep_everything_synced->IsDefaultValue())
393 return;
395 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
396 // types now, before we configure.
397 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
398 sync_prefs_.SetKeepEverythingSynced(true);
399 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
402 void ProfileSyncService::StartSyncingWithServer() {
403 if (backend_)
404 backend_->StartSyncingWithServer();
407 void ProfileSyncService::RegisterAuthNotifications() {
408 oauth2_token_service_->AddObserver(this);
409 if (signin())
410 signin()->AddObserver(this);
413 void ProfileSyncService::UnregisterAuthNotifications() {
414 if (signin())
415 signin()->RemoveObserver(this);
416 oauth2_token_service_->RemoveObserver(this);
419 void ProfileSyncService::RegisterDataTypeController(
420 DataTypeController* data_type_controller) {
421 DCHECK_EQ(
422 directory_data_type_controllers_.count(data_type_controller->type()),
423 0U);
424 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
425 data_type_controller->type()));
426 directory_data_type_controllers_[data_type_controller->type()] =
427 data_type_controller;
430 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
431 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
432 << "Duplicate registration of type " << ModelTypeToString(type);
434 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
435 // fixed and we have some way of telling whether or not this type should be
436 // enabled.
437 non_blocking_data_type_manager_.RegisterType(type, false);
440 void ProfileSyncService::InitializeNonBlockingType(
441 syncer::ModelType type,
442 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
443 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) {
444 non_blocking_data_type_manager_.InitializeType(
445 type, task_runner, type_sync_proxy);
448 bool ProfileSyncService::IsDataTypeControllerRunning(
449 syncer::ModelType type) const {
450 DataTypeController::TypeMap::const_iterator iter =
451 directory_data_type_controllers_.find(type);
452 if (iter == directory_data_type_controllers_.end()) {
453 return false;
455 return iter->second->state() == DataTypeController::RUNNING;
458 browser_sync::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
459 if (!IsDataTypeControllerRunning(syncer::SESSIONS))
460 return NULL;
461 return sessions_sync_manager_.get();
464 browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
465 return sessions_sync_manager_->GetFaviconCache();
468 browser_sync::SyncedWindowDelegatesGetter*
469 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
470 return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
473 sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
474 const {
475 return device_info_sync_service_.get();
478 sync_driver::LocalDeviceInfoProvider*
479 ProfileSyncService::GetLocalDeviceInfoProvider() {
480 return local_device_.get();
483 void ProfileSyncService::GetDataTypeControllerStates(
484 DataTypeController::StateMap* state_map) const {
485 for (DataTypeController::TypeMap::const_iterator iter =
486 directory_data_type_controllers_.begin();
487 iter != directory_data_type_controllers_.end();
488 ++iter)
489 (*state_map)[iter->first] = iter->second.get()->state();
492 SyncCredentials ProfileSyncService::GetCredentials() {
493 SyncCredentials credentials;
494 if (backend_mode_ == SYNC) {
495 credentials.email = signin_->GetEffectiveUsername();
496 DCHECK(!credentials.email.empty());
497 credentials.sync_token = access_token_;
499 if (credentials.sync_token.empty())
500 credentials.sync_token = "credentials_lost";
502 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
505 return credentials;
508 bool ProfileSyncService::ShouldDeleteSyncFolder() {
509 switch (backend_mode_) {
510 case SYNC:
511 return !HasSyncSetupCompleted();
512 case BACKUP:
513 return true;
514 case ROLLBACK:
515 return false;
516 case IDLE:
517 NOTREACHED();
518 return true;
520 return true;
523 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
524 if (!backend_) {
525 NOTREACHED();
526 return;
529 SyncCredentials credentials = GetCredentials();
531 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
532 profile_->GetRequestContext());
534 if (backend_mode_ == SYNC && delete_stale_data)
535 ClearStaleErrors();
537 scoped_ptr<syncer::UnrecoverableErrorHandler>
538 backend_unrecoverable_error_handler(
539 new browser_sync::BackendUnrecoverableErrorHandler(
540 MakeWeakHandle(weak_factory_.GetWeakPtr())));
542 backend_->Initialize(
543 this,
544 sync_thread_.Pass(),
545 GetJsEventHandler(),
546 sync_service_url_,
547 credentials,
548 delete_stale_data,
549 scoped_ptr<syncer::SyncManagerFactory>(
550 new syncer::SyncManagerFactory(GetManagerType())).Pass(),
551 backend_unrecoverable_error_handler.Pass(),
552 &browser_sync::ChromeReportUnrecoverableError,
553 network_resources_.get());
556 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
557 if (encryption_pending())
558 return true;
559 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
560 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
561 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
562 return !Intersection(preferred_types, encrypted_types).Empty();
565 void ProfileSyncService::OnProtocolEvent(
566 const syncer::ProtocolEvent& event) {
567 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
568 protocol_event_observers_,
569 OnProtocolEvent(event));
572 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
573 syncer::ModelType type,
574 const syncer::CommitCounters& counters) {
575 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
576 type_debug_info_observers_,
577 OnCommitCountersUpdated(type, counters));
580 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
581 syncer::ModelType type,
582 const syncer::UpdateCounters& counters) {
583 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
584 type_debug_info_observers_,
585 OnUpdateCountersUpdated(type, counters));
588 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
589 syncer::ModelType type,
590 const syncer::StatusCounters& counters) {
591 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
592 type_debug_info_observers_,
593 OnStatusCountersUpdated(type, counters));
596 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
597 syncer::ModelType type) {
598 DCHECK(syncer::UserTypes().Has(type));
599 if (backend_.get()) {
600 DVLOG(1) << "A data type requested sync startup, but it looks like "
601 "something else beat it to the punch.";
602 return;
605 if (!GetPreferredDataTypes().Has(type)) {
606 // We can get here as datatype SyncableServices are typically wired up
607 // to the native datatype even if sync isn't enabled.
608 DVLOG(1) << "Dropping sync startup request because type "
609 << syncer::ModelTypeToString(type) << "not enabled.";
610 return;
613 startup_controller_->OnDataTypeRequestsSyncStartup(type);
616 void ProfileSyncService::StartUpSlowBackendComponents(
617 ProfileSyncService::BackendMode mode) {
618 DCHECK_NE(IDLE, mode);
619 if (backend_mode_ == mode) {
620 return;
623 // Backend mode transition rules:
624 // * can transit from IDLE to any other non-IDLE mode.
625 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
626 // be explicitly shut down before backup/rollback starts.
627 // * can not transit out of ROLLBACK mode until rollback is finished
628 // (successfully or unsuccessfully).
629 // * can not transit out of BACKUP mode until backup is finished
630 // (successfully or unsuccessfully).
631 // * if backup is needed, can only transit to SYNC if backup is finished,
633 if (backend_mode_ == SYNC) {
634 LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
635 return;
638 if (backend_mode_ == ROLLBACK ||
639 (backend_mode_ == BACKUP && !backup_finished_)) {
640 // Wait for rollback/backup to finish before start new backend.
641 return;
644 if (mode == SYNC && NeedBackup() && !backup_finished_) {
645 if (backend_mode_ != BACKUP)
646 backup_rollback_controller_->StartBackup();
647 return;
650 DVLOG(1) << "Start backend mode: " << mode;
652 if (backend_) {
653 if (mode == SYNC)
654 ShutdownImpl(syncer::SWITCH_MODE_SYNC);
655 else
656 ShutdownImpl(syncer::STOP_SYNC);
659 backend_mode_ = mode;
661 if (backend_mode_ == BACKUP)
662 backup_start_time_ = base::Time::Now();
664 if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
665 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
666 base::Time::Now() - backup_start_time_);
667 backup_start_time_ = base::Time();
670 if (backend_mode_ == ROLLBACK)
671 ClearBrowsingDataSinceFirstSync();
672 else if (backend_mode_ == SYNC)
673 CheckSyncBackupIfNeeded();
675 base::FilePath sync_folder = backend_mode_ == SYNC ?
676 base::FilePath(kSyncDataFolderName) :
677 base::FilePath(kSyncBackupDataFolderName);
679 invalidation::InvalidationService* invalidator = NULL;
680 if (backend_mode_ == SYNC) {
681 invalidation::ProfileInvalidationProvider* provider =
682 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
683 profile_);
684 if (provider)
685 invalidator = provider->GetInvalidationService();
688 directory_path_ = profile_->GetPath().Append(sync_folder);
690 backend_.reset(
691 factory_->CreateSyncBackendHost(
692 profile_->GetDebugName(),
693 profile_,
694 invalidator,
695 sync_prefs_.AsWeakPtr(),
696 sync_folder));
698 // Initialize the backend. Every time we start up a new SyncBackendHost,
699 // we'll want to start from a fresh SyncDB, so delete any old one that might
700 // be there.
701 InitializeBackend(ShouldDeleteSyncFolder());
703 UpdateFirstSyncTimePref();
706 void ProfileSyncService::OnGetTokenSuccess(
707 const OAuth2TokenService::Request* request,
708 const std::string& access_token,
709 const base::Time& expiration_time) {
710 DCHECK_EQ(access_token_request_, request);
711 access_token_request_.reset();
712 access_token_ = access_token;
713 token_receive_time_ = base::Time::Now();
714 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
716 if (sync_prefs_.SyncHasAuthError()) {
717 sync_prefs_.SetSyncAuthError(false);
718 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
719 AUTH_ERROR_FIXED,
720 AUTH_ERROR_LIMIT);
723 if (HasSyncingBackend())
724 backend_->UpdateCredentials(GetCredentials());
725 else
726 startup_controller_->TryStart();
729 void ProfileSyncService::OnGetTokenFailure(
730 const OAuth2TokenService::Request* request,
731 const GoogleServiceAuthError& error) {
732 DCHECK_EQ(access_token_request_, request);
733 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
734 access_token_request_.reset();
735 last_get_token_error_ = error;
736 switch (error.state()) {
737 case GoogleServiceAuthError::CONNECTION_FAILED:
738 case GoogleServiceAuthError::REQUEST_CANCELED:
739 case GoogleServiceAuthError::SERVICE_ERROR:
740 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
741 // Transient error. Retry after some time.
742 request_access_token_backoff_.InformOfRequest(false);
743 next_token_request_time_ = base::Time::Now() +
744 request_access_token_backoff_.GetTimeUntilRelease();
745 request_access_token_retry_timer_.Start(
746 FROM_HERE,
747 request_access_token_backoff_.GetTimeUntilRelease(),
748 base::Bind(&ProfileSyncService::RequestAccessToken,
749 weak_factory_.GetWeakPtr()));
750 NotifyObservers();
751 break;
753 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
754 if (!sync_prefs_.SyncHasAuthError()) {
755 sync_prefs_.SetSyncAuthError(true);
756 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
757 AUTH_ERROR_ENCOUNTERED,
758 AUTH_ERROR_LIMIT);
760 // Fallthrough.
762 default: {
763 if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
764 LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
766 // Show error to user.
767 UpdateAuthErrorState(error);
772 void ProfileSyncService::OnRefreshTokenAvailable(
773 const std::string& account_id) {
774 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
775 // fixed.
776 tracked_objects::ScopedTracker tracking_profile(
777 FROM_HERE_WITH_EXPLICIT_FUNCTION(
778 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
780 if (account_id == signin_->GetAccountIdToUse())
781 OnRefreshTokensLoaded();
784 void ProfileSyncService::OnRefreshTokenRevoked(
785 const std::string& account_id) {
786 if (!IsOAuthRefreshTokenAvailable()) {
787 access_token_.clear();
788 // The additional check around IsOAuthRefreshTokenAvailable() above
789 // prevents us sounding the alarm if we actually have a valid token but
790 // a refresh attempt failed for any variety of reasons
791 // (e.g. flaky network). It's possible the token we do have is also
792 // invalid, but in that case we should already have (or can expect) an
793 // auth error sent from the sync backend.
794 UpdateAuthErrorState(
795 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
799 void ProfileSyncService::OnRefreshTokensLoaded() {
800 // This notification gets fired when OAuth2TokenService loads the tokens
801 // from storage.
802 // Initialize the backend if sync is enabled. If the sync token was
803 // not loaded, GetCredentials() will generate invalid credentials to
804 // cause the backend to generate an auth error (crbug.com/121755).
805 if (HasSyncingBackend()) {
806 RequestAccessToken();
807 } else {
808 startup_controller_->TryStart();
812 void ProfileSyncService::Shutdown() {
813 UnregisterAuthNotifications();
815 ShutdownImpl(syncer::BROWSER_SHUTDOWN);
816 if (sync_error_controller_) {
817 // Destroy the SyncErrorController when the service shuts down for good.
818 RemoveObserver(sync_error_controller_.get());
819 sync_error_controller_.reset();
822 if (sync_thread_)
823 sync_thread_->Stop();
826 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
827 if (!backend_) {
828 if (reason == syncer::ShutdownReason::DISABLE_SYNC && sync_thread_) {
829 // If the backend is already shut down when a DISABLE_SYNC happens,
830 // the data directory needs to be cleaned up here.
831 sync_thread_->message_loop()->PostTask(FROM_HERE,
832 base::Bind(&DeleteSyncDataFolder, directory_path_));
834 return;
837 if (reason == syncer::ShutdownReason::STOP_SYNC
838 || reason == syncer::ShutdownReason::DISABLE_SYNC) {
839 RemoveClientFromServer();
842 non_blocking_data_type_manager_.DisconnectSyncBackend();
844 // First, we spin down the backend to stop change processing as soon as
845 // possible.
846 base::Time shutdown_start_time = base::Time::Now();
847 backend_->StopSyncingForShutdown();
849 // Stop all data type controllers, if needed. Note that until Stop
850 // completes, it is possible in theory to have a ChangeProcessor apply a
851 // change from a native model. In that case, it will get applied to the sync
852 // database (which doesn't get destroyed until we destroy the backend below)
853 // as an unsynced change. That will be persisted, and committed on restart.
854 if (directory_data_type_manager_) {
855 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
856 // When aborting as part of shutdown, we should expect an aborted sync
857 // configure result, else we'll dcheck when we try to read the sync error.
858 expect_sync_configuration_aborted_ = true;
859 directory_data_type_manager_->Stop();
861 directory_data_type_manager_.reset();
864 // Shutdown the migrator before the backend to ensure it doesn't pull a null
865 // snapshot.
866 migrator_.reset();
867 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
869 // Move aside the backend so nobody else tries to use it while we are
870 // shutting it down.
871 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
872 if (doomed_backend) {
873 sync_thread_ = doomed_backend->Shutdown(reason);
874 doomed_backend.reset();
876 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
877 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
879 weak_factory_.InvalidateWeakPtrs();
881 if (backend_mode_ == SYNC)
882 startup_controller_->Reset(GetRegisteredDataTypes());
884 // Don't let backup block sync regardless backup succeeded or not.
885 if (backend_mode_ == BACKUP)
886 backup_finished_ = true;
888 // Sync could be blocked by rollback/backup. Post task to check whether sync
889 // should start after shutting down rollback/backup backend.
890 if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
891 reason != syncer::SWITCH_MODE_SYNC &&
892 reason != syncer::BROWSER_SHUTDOWN) {
893 base::MessageLoop::current()->PostTask(
894 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
895 startup_controller_weak_factory_.GetWeakPtr()));
898 // Clear various flags.
899 backend_mode_ = IDLE;
900 expect_sync_configuration_aborted_ = false;
901 is_auth_in_progress_ = false;
902 backend_initialized_ = false;
903 cached_passphrase_.clear();
904 encryption_pending_ = false;
905 encrypt_everything_ = false;
906 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
907 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
908 request_access_token_retry_timer_.Stop();
909 // Revert to "no auth error".
910 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
911 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
913 NotifyObservers();
916 void ProfileSyncService::DisableForUser() {
917 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
918 // PSS clients don't think we're set up while we're shutting down.
919 sync_prefs_.ClearPreferences();
920 ClearUnrecoverableError();
921 ShutdownImpl(syncer::DISABLE_SYNC);
924 bool ProfileSyncService::HasSyncSetupCompleted() const {
925 return sync_prefs_.HasSyncSetupCompleted();
928 void ProfileSyncService::SetSyncSetupCompleted() {
929 sync_prefs_.SetSyncSetupCompleted();
932 void ProfileSyncService::UpdateLastSyncedTime() {
933 sync_prefs_.SetLastSyncedTime(base::Time::Now());
936 void ProfileSyncService::NotifyObservers() {
937 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
938 OnStateChanged());
941 void ProfileSyncService::NotifySyncCycleCompleted() {
942 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_,
943 OnSyncCycleCompleted());
946 void ProfileSyncService::ClearStaleErrors() {
947 ClearUnrecoverableError();
948 last_actionable_error_ = SyncProtocolError();
949 // Clear the data type errors as well.
950 if (directory_data_type_manager_.get())
951 directory_data_type_manager_->ResetDataTypeErrors();
955 void ProfileSyncService::ClearUnrecoverableError() {
956 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
957 unrecoverable_error_message_.clear();
958 unrecoverable_error_location_ = tracked_objects::Location();
961 void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) {
962 if (directory_data_type_controllers_.count(data_type) > 0)
963 return;
964 NOTREACHED();
967 // An invariant has been violated. Transition to an error state where we try
968 // to do as little work as possible, to avoid further corruption or crashes.
969 void ProfileSyncService::OnUnrecoverableError(
970 const tracked_objects::Location& from_here,
971 const std::string& message) {
972 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
973 // interface are assumed to originate within the syncer.
974 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
975 OnUnrecoverableErrorImpl(from_here, message, true);
978 void ProfileSyncService::OnUnrecoverableErrorImpl(
979 const tracked_objects::Location& from_here,
980 const std::string& message,
981 bool delete_sync_database) {
982 DCHECK(HasUnrecoverableError());
983 unrecoverable_error_message_ = message;
984 unrecoverable_error_location_ = from_here;
986 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
987 unrecoverable_error_reason_,
988 ERROR_REASON_LIMIT);
989 std::string location;
990 from_here.Write(true, true, &location);
991 LOG(ERROR)
992 << "Unrecoverable error detected at " << location
993 << " -- ProfileSyncService unusable: " << message;
995 // Shut all data types down.
996 base::MessageLoop::current()->PostTask(FROM_HERE,
997 base::Bind(&ProfileSyncService::ShutdownImpl,
998 weak_factory_.GetWeakPtr(),
999 delete_sync_database ?
1000 syncer::DISABLE_SYNC : syncer::STOP_SYNC));
1003 void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
1004 DCHECK(backend_initialized_);
1005 directory_data_type_manager_->ReenableType(type);
1008 void ProfileSyncService::UpdateBackendInitUMA(bool success) {
1009 if (backend_mode_ != SYNC)
1010 return;
1012 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
1014 if (is_first_time_sync_configure_) {
1015 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
1016 } else {
1017 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
1020 base::Time on_backend_initialized_time = base::Time::Now();
1021 base::TimeDelta delta = on_backend_initialized_time -
1022 startup_controller_->start_backend_time();
1023 if (is_first_time_sync_configure_) {
1024 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1025 } else {
1026 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1030 void ProfileSyncService::PostBackendInitialization() {
1031 // Never get here for backup / restore.
1032 DCHECK_EQ(backend_mode_, SYNC);
1034 if (last_backup_time_) {
1035 DCHECK(device_info_sync_service_);
1036 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1039 if (protocol_event_observers_.might_have_observers()) {
1040 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1043 non_blocking_data_type_manager_.ConnectSyncBackend(
1044 backend_->GetSyncContextProxy());
1046 if (type_debug_info_observers_.might_have_observers()) {
1047 backend_->EnableDirectoryTypeDebugInfoForwarding();
1050 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1051 // backend is initialized. We want to call this before notifying observers in
1052 // case this operation affects the "passphrase required" status.
1053 ConsumeCachedPassphraseIfPossible();
1055 // The very first time the backend initializes is effectively the first time
1056 // we can say we successfully "synced". LastSyncedTime will only be null in
1057 // this case, because the pref wasn't restored on StartUp.
1058 if (sync_prefs_.GetLastSyncedTime().is_null()) {
1059 UpdateLastSyncedTime();
1062 if (startup_controller_->auto_start_enabled() && !FirstSetupInProgress()) {
1063 // Backend is initialized but we're not in sync setup, so this must be an
1064 // autostart - mark our sync setup as completed and we'll start syncing
1065 // below.
1066 SetSyncSetupCompleted();
1069 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1070 // data type configuration because observer may flag setup as complete and
1071 // trigger data type configuration.
1072 if (HasSyncSetupCompleted()) {
1073 ConfigureDataTypeManager();
1074 } else {
1075 DCHECK(FirstSetupInProgress());
1078 NotifyObservers();
1081 void ProfileSyncService::OnBackendInitialized(
1082 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1083 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1084 debug_info_listener,
1085 const std::string& cache_guid,
1086 bool success) {
1087 UpdateBackendInitUMA(success);
1089 if (!success) {
1090 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1091 // and surface error UI to alert the user sync has stopped.
1092 // Keep the directory around for now so that on restart we will retry
1093 // again and potentially succeed in presence of transient file IO failures
1094 // or permissions issues, etc.
1096 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1097 // Unlike every other UnrecoverableError, it does not delete our sync data.
1098 // This exception made sense at the time it was implemented, but our new
1099 // directory corruption recovery mechanism makes it obsolete. By the time
1100 // we get here, we will have already tried and failed to delete the
1101 // directory. It would be no big deal if we tried to delete it again.
1102 OnInternalUnrecoverableError(FROM_HERE,
1103 "BackendInitialize failure",
1104 false,
1105 ERROR_REASON_BACKEND_INIT_FAILURE);
1106 return;
1109 backend_initialized_ = true;
1111 sync_js_controller_.AttachJsBackend(js_backend);
1112 debug_info_listener_ = debug_info_listener;
1114 SigninClient* signin_client =
1115 ChromeSigninClientFactory::GetForProfile(profile_);
1116 DCHECK(signin_client);
1117 std::string signin_scoped_device_id =
1118 signin_client->GetSigninScopedDeviceId();
1120 // Initialize local device info.
1121 local_device_->Initialize(cache_guid, signin_scoped_device_id);
1123 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1124 non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1126 // Give the DataTypeControllers a handle to the now initialized backend
1127 // as a UserShare.
1128 for (DataTypeController::TypeMap::iterator it =
1129 directory_data_type_controllers_.begin();
1130 it != directory_data_type_controllers_.end(); ++it) {
1131 it->second->OnUserShareReady(GetUserShare());
1134 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1135 ConfigureDataTypeManager();
1136 else
1137 PostBackendInitialization();
1140 void ProfileSyncService::OnSyncCycleCompleted() {
1141 UpdateLastSyncedTime();
1142 if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1143 // Trigger garbage collection of old sessions now that we've downloaded
1144 // any new session data.
1145 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
1146 &SessionsSyncManager::DoGarbageCollection,
1147 base::AsWeakPtr(sessions_sync_manager_.get())));
1149 DVLOG(2) << "Notifying observers sync cycle completed";
1150 NotifySyncCycleCompleted();
1153 void ProfileSyncService::OnExperimentsChanged(
1154 const syncer::Experiments& experiments) {
1155 if (current_experiments_.Matches(experiments))
1156 return;
1158 current_experiments_ = experiments;
1160 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1161 experiments.gcm_invalidations_enabled);
1162 profile()->GetPrefs()->SetBoolean(
1163 autofill::prefs::kAutofillWalletSyncExperimentEnabled,
1164 experiments.wallet_sync_enabled);
1166 // If this is a first time sync for a client, this will be called before
1167 // OnBackendInitialized() to ensure the new datatypes are available at sync
1168 // setup. As a result, the migrator won't exist yet. This is fine because for
1169 // first time sync cases we're only concerned with making the datatype
1170 // available.
1171 if (migrator_.get() &&
1172 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1173 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1174 return;
1177 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1178 syncer::ModelTypeSet to_add;
1179 const syncer::ModelTypeSet to_register =
1180 Difference(to_add, registered_types);
1181 DVLOG(2) << "OnExperimentsChanged called with types: "
1182 << syncer::ModelTypeSetToString(to_add);
1183 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register);
1185 for (syncer::ModelTypeSet::Iterator it = to_register.First();
1186 it.Good(); it.Inc()) {
1187 // Received notice to enable experimental type. Check if the type is
1188 // registered, and if not register a new datatype controller.
1189 RegisterNewDataType(it.Get());
1192 // Check if the user has "Keep Everything Synced" enabled. If so, we want
1193 // to turn on all experimental types if they're not already on. Otherwise we
1194 // leave them off.
1195 // Note: if any types are already registered, we don't turn them on. This
1196 // covers the case where we're already in the process of reconfiguring
1197 // to turn an experimental type on.
1198 if (sync_prefs_.HasKeepEverythingSynced()) {
1199 // Mark all data types as preferred.
1200 sync_prefs_.SetPreferredDataTypes(registered_types, registered_types);
1202 // Only automatically turn on types if we have already finished set up.
1203 // Otherwise, just leave the experimental types on by default.
1204 if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_) {
1205 DVLOG(1) << "Dynamically enabling new datatypes: "
1206 << syncer::ModelTypeSetToString(to_register);
1207 OnMigrationNeededForTypes(to_register);
1212 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1213 is_auth_in_progress_ = false;
1214 last_auth_error_ = error;
1216 NotifyObservers();
1219 namespace {
1221 AuthError ConnectionStatusToAuthError(
1222 syncer::ConnectionStatus status) {
1223 switch (status) {
1224 case syncer::CONNECTION_OK:
1225 return AuthError::AuthErrorNone();
1226 break;
1227 case syncer::CONNECTION_AUTH_ERROR:
1228 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1229 break;
1230 case syncer::CONNECTION_SERVER_ERROR:
1231 return AuthError(AuthError::CONNECTION_FAILED);
1232 break;
1233 default:
1234 NOTREACHED();
1235 return AuthError(AuthError::CONNECTION_FAILED);
1239 } // namespace
1241 void ProfileSyncService::OnConnectionStatusChange(
1242 syncer::ConnectionStatus status) {
1243 connection_status_update_time_ = base::Time::Now();
1244 connection_status_ = status;
1245 if (status == syncer::CONNECTION_AUTH_ERROR) {
1246 // Sync server returned error indicating that access token is invalid. It
1247 // could be either expired or access is revoked. Let's request another
1248 // access token and if access is revoked then request for token will fail
1249 // with corresponding error. If access token is repeatedly reported
1250 // invalid, there may be some issues with server, e.g. authentication
1251 // state is inconsistent on sync and token server. In that case, we
1252 // backoff token requests exponentially to avoid hammering token server
1253 // too much and to avoid getting same token due to token server's caching
1254 // policy. |request_access_token_retry_timer_| is used to backoff request
1255 // triggered by both auth error and failure talking to GAIA server.
1256 // Therefore, we're likely to reach the backoff ceiling more quickly than
1257 // you would expect from looking at the BackoffPolicy if both types of
1258 // errors happen. We shouldn't receive two errors back-to-back without
1259 // attempting a token/sync request in between, thus crank up request delay
1260 // unnecessary. This is because we won't make a sync request if we hit an
1261 // error until GAIA succeeds at sending a new token, and we won't request
1262 // a new token unless sync reports a token failure. But to be safe, don't
1263 // schedule request if this happens.
1264 if (request_access_token_retry_timer_.IsRunning()) {
1265 // The timer to perform a request later is already running; nothing
1266 // further needs to be done at this point.
1267 } else if (request_access_token_backoff_.failure_count() == 0) {
1268 // First time request without delay. Currently invalid token is used
1269 // to initialize sync backend and we'll always end up here. We don't
1270 // want to delay initialization.
1271 request_access_token_backoff_.InformOfRequest(false);
1272 RequestAccessToken();
1273 } else {
1274 request_access_token_backoff_.InformOfRequest(false);
1275 request_access_token_retry_timer_.Start(
1276 FROM_HERE,
1277 request_access_token_backoff_.GetTimeUntilRelease(),
1278 base::Bind(&ProfileSyncService::RequestAccessToken,
1279 weak_factory_.GetWeakPtr()));
1281 } else {
1282 // Reset backoff time after successful connection.
1283 if (status == syncer::CONNECTION_OK) {
1284 // Request shouldn't be scheduled at this time. But if it is, it's
1285 // possible that sync flips between OK and auth error states rapidly,
1286 // thus hammers token server. To be safe, only reset backoff delay when
1287 // no scheduled request.
1288 if (request_access_token_retry_timer_.IsRunning()) {
1289 NOTREACHED();
1290 } else {
1291 request_access_token_backoff_.Reset();
1295 const GoogleServiceAuthError auth_error =
1296 ConnectionStatusToAuthError(status);
1297 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1298 UpdateAuthErrorState(auth_error);
1302 void ProfileSyncService::StopSyncingPermanently() {
1303 sync_prefs_.SetStartSuppressed(true);
1304 DisableForUser();
1307 void ProfileSyncService::OnPassphraseRequired(
1308 syncer::PassphraseRequiredReason reason,
1309 const sync_pb::EncryptedData& pending_keys) {
1310 DCHECK(backend_.get());
1311 DCHECK(backend_->IsNigoriEnabled());
1313 // TODO(lipalani) : add this check to other locations as well.
1314 if (HasUnrecoverableError()) {
1315 // When unrecoverable error is detected we post a task to shutdown the
1316 // backend. The task might not have executed yet.
1317 return;
1320 DVLOG(1) << "Passphrase required with reason: "
1321 << syncer::PassphraseRequiredReasonToString(reason);
1322 passphrase_required_reason_ = reason;
1324 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1325 if (directory_data_type_manager_) {
1326 // Reconfigure without the encrypted types (excluded implicitly via the
1327 // failed datatypes handler).
1328 directory_data_type_manager_->Configure(types,
1329 syncer::CONFIGURE_REASON_CRYPTO);
1332 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1334 // Notify observers that the passphrase status may have changed.
1335 NotifyObservers();
1338 void ProfileSyncService::OnPassphraseAccepted() {
1339 DVLOG(1) << "Received OnPassphraseAccepted.";
1341 // If the pending keys were resolved via keystore, it's possible we never
1342 // consumed our cached passphrase. Clear it now.
1343 if (!cached_passphrase_.empty())
1344 cached_passphrase_.clear();
1346 // Reset passphrase_required_reason_ since we know we no longer require the
1347 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1348 // because that can be called by OnPassphraseRequired() if no encrypted data
1349 // types are enabled, and we don't want to clobber the true passphrase error.
1350 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1352 // Make sure the data types that depend on the passphrase are started at
1353 // this time.
1354 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1355 if (directory_data_type_manager_) {
1356 // Re-enable any encrypted types if necessary.
1357 directory_data_type_manager_->Configure(types,
1358 syncer::CONFIGURE_REASON_CRYPTO);
1361 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1363 NotifyObservers();
1366 void ProfileSyncService::OnEncryptedTypesChanged(
1367 syncer::ModelTypeSet encrypted_types,
1368 bool encrypt_everything) {
1369 encrypted_types_ = encrypted_types;
1370 encrypt_everything_ = encrypt_everything;
1371 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1372 DVLOG(1) << "Encrypted types changed to "
1373 << syncer::ModelTypeSetToString(encrypted_types_)
1374 << " (encrypt everything is set to "
1375 << (encrypt_everything_ ? "true" : "false") << ")";
1376 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1378 NotifyObservers();
1381 void ProfileSyncService::OnEncryptionComplete() {
1382 DVLOG(1) << "Encryption complete";
1383 if (encryption_pending_ && encrypt_everything_) {
1384 encryption_pending_ = false;
1385 // This is to nudge the integration tests when encryption is
1386 // finished.
1387 NotifyObservers();
1391 void ProfileSyncService::OnMigrationNeededForTypes(
1392 syncer::ModelTypeSet types) {
1393 DCHECK(backend_initialized_);
1394 DCHECK(directory_data_type_manager_.get());
1396 // Migrator must be valid, because we don't sync until it is created and this
1397 // callback originates from a sync cycle.
1398 migrator_->MigrateTypes(types);
1401 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1402 last_actionable_error_ = error;
1403 DCHECK_NE(last_actionable_error_.action,
1404 syncer::UNKNOWN_ACTION);
1405 switch (error.action) {
1406 case syncer::UPGRADE_CLIENT:
1407 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1408 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1409 case syncer::STOP_AND_RESTART_SYNC:
1410 // TODO(lipalani) : if setup in progress we want to display these
1411 // actions in the popup. The current experience might not be optimal for
1412 // the user. We just dismiss the dialog.
1413 if (startup_controller_->setup_in_progress()) {
1414 StopSyncingPermanently();
1415 expect_sync_configuration_aborted_ = true;
1417 // Trigger an unrecoverable error to stop syncing.
1418 OnInternalUnrecoverableError(FROM_HERE,
1419 last_actionable_error_.error_description,
1420 true,
1421 ERROR_REASON_ACTIONABLE_ERROR);
1422 break;
1423 case syncer::DISABLE_SYNC_AND_ROLLBACK:
1424 backup_rollback_controller_->OnRollbackReceived();
1425 // Fall through to shutdown backend and sign user out.
1426 case syncer::DISABLE_SYNC_ON_CLIENT:
1427 StopSyncingPermanently();
1428 #if !defined(OS_CHROMEOS)
1429 // On desktop Chrome, sign out the user after a dashboard clear.
1430 // Skip sign out on ChromeOS/Android.
1431 if (!startup_controller_->auto_start_enabled()) {
1432 SigninManagerFactory::GetForProfile(profile_)->SignOut(
1433 signin_metrics::SERVER_FORCED_DISABLE);
1435 #endif
1436 break;
1437 case syncer::ROLLBACK_DONE:
1438 backup_rollback_controller_->OnRollbackDone();
1439 break;
1440 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1441 // Sync disabled by domain admin. we should stop syncing until next
1442 // restart.
1443 sync_disabled_by_admin_ = true;
1444 ShutdownImpl(syncer::DISABLE_SYNC);
1445 break;
1446 default:
1447 NOTREACHED();
1449 NotifyObservers();
1451 if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1452 (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1453 !backup_rollback_controller_->StartRollback())) {
1454 // Clean up backup data for sign-out only or when rollback is disabled.
1455 CleanUpBackup();
1456 } else if (error.action == syncer::ROLLBACK_DONE) {
1457 // Shut down ROLLBACK backend and delete backup DB.
1458 ShutdownImpl(syncer::DISABLE_SYNC);
1459 sync_prefs_.ClearFirstSyncTime();
1463 void ProfileSyncService::OnConfigureDone(
1464 const DataTypeManager::ConfigureResult& result) {
1465 configure_status_ = result.status;
1466 data_type_status_table_ = result.data_type_status_table;
1468 if (backend_mode_ != SYNC) {
1469 if (configure_status_ == DataTypeManager::OK) {
1470 StartSyncingWithServer();
1472 // Backup is done after models are associated.
1473 if (backend_mode_ == BACKUP)
1474 backup_finished_ = true;
1476 // Asynchronously check whether sync needs to start.
1477 base::MessageLoop::current()->PostTask(
1478 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1479 startup_controller_weak_factory_.GetWeakPtr()));
1480 } else if (!expect_sync_configuration_aborted_) {
1481 DVLOG(1) << "Backup/rollback backend failed to configure.";
1482 ShutdownImpl(syncer::STOP_SYNC);
1485 return;
1488 // We should have cleared our cached passphrase before we get here (in
1489 // OnBackendInitialized()).
1490 DCHECK(cached_passphrase_.empty());
1492 if (!sync_configure_start_time_.is_null()) {
1493 if (result.status == DataTypeManager::OK) {
1494 base::Time sync_configure_stop_time = base::Time::Now();
1495 base::TimeDelta delta = sync_configure_stop_time -
1496 sync_configure_start_time_;
1497 if (is_first_time_sync_configure_) {
1498 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1499 } else {
1500 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1501 delta);
1504 sync_configure_start_time_ = base::Time();
1507 // Notify listeners that configuration is done.
1508 content::NotificationService::current()->Notify(
1509 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1510 content::Source<ProfileSyncService>(this),
1511 content::NotificationService::NoDetails());
1513 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1514 // The possible status values:
1515 // ABORT - Configuration was aborted. This is not an error, if
1516 // initiated by user.
1517 // OK - Some or all types succeeded.
1518 // Everything else is an UnrecoverableError. So treat it as such.
1520 // First handle the abort case.
1521 if (configure_status_ == DataTypeManager::ABORTED &&
1522 expect_sync_configuration_aborted_) {
1523 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1524 expect_sync_configuration_aborted_ = false;
1525 return;
1528 // Handle unrecoverable error.
1529 if (configure_status_ != DataTypeManager::OK) {
1530 // Something catastrophic had happened. We should only have one
1531 // error representing it.
1532 syncer::SyncError error =
1533 data_type_status_table_.GetUnrecoverableError();
1534 DCHECK(error.IsSet());
1535 std::string message =
1536 "Sync configuration failed with status " +
1537 DataTypeManager::ConfigureStatusToString(configure_status_) +
1538 " caused by " +
1539 syncer::ModelTypeSetToString(
1540 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1541 ": " + error.message();
1542 LOG(ERROR) << "ProfileSyncService error: " << message;
1543 OnInternalUnrecoverableError(error.location(),
1544 message,
1545 true,
1546 ERROR_REASON_CONFIGURATION_FAILURE);
1547 return;
1550 // We should never get in a state where we have no encrypted datatypes
1551 // enabled, and yet we still think we require a passphrase for decryption.
1552 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1553 !IsEncryptedDatatypeEnabled()));
1555 // This must be done before we start syncing with the server to avoid
1556 // sending unencrypted data up on a first time sync.
1557 if (encryption_pending_)
1558 backend_->EnableEncryptEverything();
1559 NotifyObservers();
1561 if (migrator_.get() &&
1562 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1563 // Migration in progress. Let the migrator know we just finished
1564 // configuring something. It will be up to the migrator to call
1565 // StartSyncingWithServer() if migration is now finished.
1566 migrator_->OnConfigureDone(result);
1567 } else {
1568 StartSyncingWithServer();
1572 void ProfileSyncService::OnConfigureStart() {
1573 sync_configure_start_time_ = base::Time::Now();
1574 NotifyObservers();
1577 ProfileSyncService::SyncStatusSummary
1578 ProfileSyncService::QuerySyncStatusSummary() {
1579 if (HasUnrecoverableError()) {
1580 return UNRECOVERABLE_ERROR;
1581 } else if (!backend_) {
1582 return NOT_ENABLED;
1583 } else if (backend_mode_ == BACKUP) {
1584 return BACKUP_USER_DATA;
1585 } else if (backend_mode_ == ROLLBACK) {
1586 return ROLLBACK_USER_DATA;
1587 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1588 return SETUP_INCOMPLETE;
1589 } else if (
1590 backend_.get() && HasSyncSetupCompleted() &&
1591 directory_data_type_manager_.get() &&
1592 directory_data_type_manager_->state() == DataTypeManager::STOPPED) {
1593 return DATATYPES_NOT_INITIALIZED;
1594 } else if (SyncActive()) {
1595 return INITIALIZED;
1597 return UNKNOWN_ERROR;
1600 std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1601 SyncStatusSummary status = QuerySyncStatusSummary();
1603 std::string config_status_str =
1604 configure_status_ != DataTypeManager::UNKNOWN ?
1605 DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1607 switch (status) {
1608 case UNRECOVERABLE_ERROR:
1609 return "Unrecoverable error detected";
1610 case NOT_ENABLED:
1611 return "Syncing not enabled";
1612 case SETUP_INCOMPLETE:
1613 return "First time sync setup incomplete";
1614 case DATATYPES_NOT_INITIALIZED:
1615 return "Datatypes not fully initialized";
1616 case INITIALIZED:
1617 return "Sync service initialized";
1618 case BACKUP_USER_DATA:
1619 return "Backing-up user data. Status: " + config_status_str;
1620 case ROLLBACK_USER_DATA:
1621 return "Restoring user data. Status: " + config_status_str;
1622 default:
1623 return "Status unknown: Internal error?";
1627 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1628 return startup_controller_->GetBackendInitializationStateString();
1631 bool ProfileSyncService::auto_start_enabled() const {
1632 return startup_controller_->auto_start_enabled();
1635 bool ProfileSyncService::setup_in_progress() const {
1636 return startup_controller_->setup_in_progress();
1639 bool ProfileSyncService::QueryDetailedSyncStatus(
1640 SyncBackendHost::Status* result) {
1641 if (backend_.get() && backend_initialized_) {
1642 *result = backend_->GetDetailedStatus();
1643 return true;
1644 } else {
1645 SyncBackendHost::Status status;
1646 status.sync_protocol_error = last_actionable_error_;
1647 *result = status;
1648 return false;
1652 const AuthError& ProfileSyncService::GetAuthError() const {
1653 return last_auth_error_;
1656 bool ProfileSyncService::FirstSetupInProgress() const {
1657 return !HasSyncSetupCompleted() && startup_controller_->setup_in_progress();
1660 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1661 // This method is a no-op if |setup_in_progress_| remains unchanged.
1662 if (startup_controller_->setup_in_progress() == setup_in_progress)
1663 return;
1665 startup_controller_->set_setup_in_progress(setup_in_progress);
1666 if (!setup_in_progress && backend_initialized())
1667 ReconfigureDatatypeManager();
1668 NotifyObservers();
1671 bool ProfileSyncService::SyncActive() const {
1672 return backend_initialized_ && backend_mode_ == SYNC &&
1673 directory_data_type_manager_ &&
1674 directory_data_type_manager_->state() != DataTypeManager::STOPPED;
1677 bool ProfileSyncService::backend_initialized() const {
1678 return backend_initialized_;
1681 ProfileSyncService::BackendMode ProfileSyncService::backend_mode() const {
1682 return backend_mode_;
1685 bool ProfileSyncService::ConfigurationDone() const {
1686 return directory_data_type_manager_ &&
1687 directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
1690 bool ProfileSyncService::waiting_for_auth() const {
1691 return is_auth_in_progress_;
1694 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1695 return current_experiments_;
1698 bool ProfileSyncService::HasUnrecoverableError() const {
1699 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1702 bool ProfileSyncService::IsPassphraseRequired() const {
1703 return passphrase_required_reason_ !=
1704 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1707 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1708 // If there is an encrypted datatype enabled and we don't have the proper
1709 // passphrase, we must prompt the user for a passphrase. The only way for the
1710 // user to avoid entering their passphrase is to disable the encrypted types.
1711 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1714 base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1715 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
1716 if (last_synced_time.is_null())
1717 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1719 base::TimeDelta time_since_last_sync = base::Time::Now() - last_synced_time;
1721 if (time_since_last_sync < base::TimeDelta::FromMinutes(1))
1722 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1724 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1725 ui::TimeFormat::LENGTH_SHORT,
1726 time_since_last_sync);
1729 void ProfileSyncService::UpdateSelectedTypesHistogram(
1730 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1731 if (!HasSyncSetupCompleted() ||
1732 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1733 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1736 // Only log the data types that are shown in the sync settings ui.
1737 // Note: the order of these types must match the ordering of
1738 // the respective types in ModelType
1739 const sync_driver::user_selectable_type::UserSelectableSyncType
1740 user_selectable_types[] = {
1741 sync_driver::user_selectable_type::BOOKMARKS,
1742 sync_driver::user_selectable_type::PREFERENCES,
1743 sync_driver::user_selectable_type::PASSWORDS,
1744 sync_driver::user_selectable_type::AUTOFILL,
1745 sync_driver::user_selectable_type::THEMES,
1746 sync_driver::user_selectable_type::TYPED_URLS,
1747 sync_driver::user_selectable_type::EXTENSIONS,
1748 sync_driver::user_selectable_type::APPS,
1749 sync_driver::user_selectable_type::WIFI_CREDENTIAL,
1750 sync_driver::user_selectable_type::PROXY_TABS,
1753 static_assert(35 == syncer::MODEL_TYPE_COUNT,
1754 "custom config histogram must be updated");
1756 if (!sync_everything) {
1757 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1759 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1760 syncer::ModelTypeSet::Iterator it = type_set.First();
1762 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1764 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1765 ++i, it.Inc()) {
1766 const syncer::ModelType type = it.Get();
1767 if (chosen_types.Has(type) &&
1768 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1769 // Selected type has changed - log it.
1770 UMA_HISTOGRAM_ENUMERATION(
1771 "Sync.CustomSync",
1772 user_selectable_types[i],
1773 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1779 #if defined(OS_CHROMEOS)
1780 void ProfileSyncService::RefreshSpareBootstrapToken(
1781 const std::string& passphrase) {
1782 sync_driver::SystemEncryptor encryptor;
1783 syncer::Cryptographer temp_cryptographer(&encryptor);
1784 // The first 2 params (hostname and username) doesn't have any effect here.
1785 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1787 std::string bootstrap_token;
1788 if (!temp_cryptographer.AddKey(key_params)) {
1789 NOTREACHED() << "Failed to add key to cryptographer.";
1791 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1792 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1794 #endif
1796 void ProfileSyncService::OnUserChoseDatatypes(
1797 bool sync_everything,
1798 syncer::ModelTypeSet chosen_types) {
1799 if (!backend_.get() && !HasUnrecoverableError()) {
1800 NOTREACHED();
1801 return;
1804 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1805 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1807 if (directory_data_type_manager_.get())
1808 directory_data_type_manager_->ResetDataTypeErrors();
1809 ChangePreferredDataTypes(chosen_types);
1812 void ProfileSyncService::ChangePreferredDataTypes(
1813 syncer::ModelTypeSet preferred_types) {
1815 DVLOG(1) << "ChangePreferredDataTypes invoked";
1816 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1817 const syncer::ModelTypeSet registered_preferred_types =
1818 Intersection(registered_types, preferred_types);
1819 sync_prefs_.SetPreferredDataTypes(registered_types,
1820 registered_preferred_types);
1822 // Now reconfigure the DTM.
1823 ReconfigureDatatypeManager();
1825 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1826 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1827 // which types should be enabled and when.
1830 syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1831 if (!SyncActive() || !ConfigurationDone())
1832 return syncer::ModelTypeSet();
1833 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1834 const syncer::ModelTypeSet failed_types =
1835 data_type_status_table_.GetFailedTypes();
1836 return Difference(preferred_types, failed_types);
1839 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1840 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1841 const syncer::ModelTypeSet preferred_types =
1842 sync_prefs_.GetPreferredDataTypes(registered_types);
1843 const syncer::ModelTypeSet enforced_types =
1844 Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1845 return Union(preferred_types, enforced_types);
1848 syncer::ModelTypeSet
1849 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1850 const syncer::ModelTypeSet registered_directory_types =
1851 GetRegisteredDirectoryDataTypes();
1852 const syncer::ModelTypeSet preferred_types =
1853 sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1854 const syncer::ModelTypeSet enforced_types =
1855 Intersection(GetDataTypesFromPreferenceProviders(),
1856 registered_directory_types);
1857 return Union(preferred_types, enforced_types);
1860 syncer::ModelTypeSet
1861 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1862 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1865 syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1866 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1867 // we'll need another way to distinguish user-choosable types from
1868 // programmatically-enabled types.
1869 return GetDataTypesFromPreferenceProviders();
1872 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1873 return Union(GetRegisteredDirectoryDataTypes(),
1874 GetRegisteredNonBlockingDataTypes());
1877 syncer::ModelTypeSet
1878 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1879 syncer::ModelTypeSet registered_types;
1880 // The directory_data_type_controllers_ are determined by command-line flags;
1881 // that's effectively what controls the values returned here.
1882 for (DataTypeController::TypeMap::const_iterator it =
1883 directory_data_type_controllers_.begin();
1884 it != directory_data_type_controllers_.end(); ++it) {
1885 registered_types.Put(it->first);
1887 return registered_types;
1890 syncer::ModelTypeSet
1891 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1892 return non_blocking_data_type_manager_.GetRegisteredTypes();
1895 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1896 syncer::PassphraseType passphrase_type = GetPassphraseType();
1897 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1898 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1901 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1902 return backend_->GetPassphraseType();
1905 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1906 return backend_->GetExplicitPassphraseTime();
1909 bool ProfileSyncService::IsCryptographerReady(
1910 const syncer::BaseTransaction* trans) const {
1911 return backend_.get() && backend_->IsCryptographerReady(trans);
1914 void ProfileSyncService::ConfigurePriorityDataTypes() {
1915 const syncer::ModelTypeSet priority_types =
1916 Intersection(GetPreferredDirectoryDataTypes(),
1917 syncer::PriorityUserTypes());
1918 if (!priority_types.Empty()) {
1919 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1920 syncer::CONFIGURE_REASON_RECONFIGURATION :
1921 syncer::CONFIGURE_REASON_NEW_CLIENT;
1922 directory_data_type_manager_->Configure(priority_types, reason);
1926 void ProfileSyncService::ConfigureDataTypeManager() {
1927 // Don't configure datatypes if the setup UI is still on the screen - this
1928 // is to help multi-screen setting UIs (like iOS) where they don't want to
1929 // start syncing data until the user is done configuring encryption options,
1930 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1931 // SetSetupInProgress(false).
1932 if (backend_mode_ == SYNC && startup_controller_->setup_in_progress())
1933 return;
1935 bool restart = false;
1936 if (!directory_data_type_manager_) {
1937 restart = true;
1938 directory_data_type_manager_.reset(
1939 factory_->CreateDataTypeManager(debug_info_listener_,
1940 &directory_data_type_controllers_,
1941 this,
1942 backend_.get(),
1943 this));
1945 // We create the migrator at the same time.
1946 migrator_.reset(
1947 new browser_sync::BackendMigrator(
1948 profile_->GetDebugName(), GetUserShare(),
1949 this, directory_data_type_manager_.get(),
1950 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1951 base::Unretained(this))));
1954 syncer::ModelTypeSet types;
1955 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1956 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1957 types = syncer::BackupTypes();
1958 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1959 } else {
1960 types = GetPreferredDirectoryDataTypes();
1961 if (!HasSyncSetupCompleted()) {
1962 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1963 } else if (restart) {
1964 // Datatype downloads on restart are generally due to newly supported
1965 // datatypes (although it's also possible we're picking up where a failed
1966 // previous configuration left off).
1967 // TODO(sync): consider detecting configuration recovery and setting
1968 // the reason here appropriately.
1969 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1970 } else {
1971 // The user initiated a reconfiguration (either to add or remove types).
1972 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1976 directory_data_type_manager_->Configure(types, reason);
1979 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1980 if (backend_.get() && backend_initialized_) {
1981 return backend_->GetUserShare();
1983 NOTREACHED();
1984 return NULL;
1987 syncer::sessions::SyncSessionSnapshot
1988 ProfileSyncService::GetLastSessionSnapshot() const {
1989 if (backend_)
1990 return backend_->GetLastSessionSnapshot();
1991 return syncer::sessions::SyncSessionSnapshot();
1994 bool ProfileSyncService::HasUnsyncedItems() const {
1995 if (HasSyncingBackend() && backend_initialized_) {
1996 return backend_->HasUnsyncedItems();
1998 NOTREACHED();
1999 return false;
2002 browser_sync::BackendMigrator*
2003 ProfileSyncService::GetBackendMigratorForTest() {
2004 return migrator_.get();
2007 void ProfileSyncService::GetModelSafeRoutingInfo(
2008 syncer::ModelSafeRoutingInfo* out) const {
2009 if (backend_.get() && backend_initialized_) {
2010 backend_->GetModelSafeRoutingInfo(out);
2011 } else {
2012 NOTREACHED();
2016 base::Value* ProfileSyncService::GetTypeStatusMap() const {
2017 scoped_ptr<base::ListValue> result(new base::ListValue());
2019 if (!backend_.get() || !backend_initialized_) {
2020 return result.release();
2023 DataTypeStatusTable::TypeErrorMap error_map =
2024 data_type_status_table_.GetAllErrors();
2025 ModelTypeSet active_types;
2026 ModelTypeSet passive_types;
2027 ModelSafeRoutingInfo routing_info;
2028 backend_->GetModelSafeRoutingInfo(&routing_info);
2029 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
2030 it != routing_info.end(); ++it) {
2031 if (it->second == syncer::GROUP_PASSIVE) {
2032 passive_types.Put(it->first);
2033 } else {
2034 active_types.Put(it->first);
2038 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
2039 ModelTypeSet &throttled_types(detailed_status.throttled_types);
2040 ModelTypeSet registered = GetRegisteredDataTypes();
2041 scoped_ptr<base::DictionaryValue> type_status_header(
2042 new base::DictionaryValue());
2044 type_status_header->SetString("name", "Model Type");
2045 type_status_header->SetString("status", "header");
2046 type_status_header->SetString("value", "Group Type");
2047 type_status_header->SetString("num_entries", "Total Entries");
2048 type_status_header->SetString("num_live", "Live Entries");
2049 result->Append(type_status_header.release());
2051 scoped_ptr<base::DictionaryValue> type_status;
2052 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2053 ModelType type = it.Get();
2055 type_status.reset(new base::DictionaryValue());
2056 type_status->SetString("name", ModelTypeToString(type));
2058 if (error_map.find(type) != error_map.end()) {
2059 const syncer::SyncError &error = error_map.find(type)->second;
2060 DCHECK(error.IsSet());
2061 switch (error.GetSeverity()) {
2062 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2063 std::string error_text = "Error: " + error.location().ToString() +
2064 ", " + error.GetMessagePrefix() + error.message();
2065 type_status->SetString("status", "error");
2066 type_status->SetString("value", error_text);
2068 break;
2069 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2070 type_status->SetString("status", "disabled");
2071 type_status->SetString("value", error.message());
2072 break;
2073 default:
2074 NOTREACHED() << "Unexpected error severity.";
2075 break;
2077 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2078 // Show a proxy type in "ok" state unless it is disabled by user.
2079 DCHECK(!throttled_types.Has(type));
2080 type_status->SetString("status", "ok");
2081 type_status->SetString("value", "Passive");
2082 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2083 type_status->SetString("status", "warning");
2084 type_status->SetString("value", "Passive, Throttled");
2085 } else if (passive_types.Has(type)) {
2086 type_status->SetString("status", "warning");
2087 type_status->SetString("value", "Passive");
2088 } else if (throttled_types.Has(type)) {
2089 type_status->SetString("status", "warning");
2090 type_status->SetString("value", "Throttled");
2091 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2092 type_status->SetString("status", "ok");
2093 type_status->SetString("value", "Non-Blocking");
2094 } else if (active_types.Has(type)) {
2095 type_status->SetString("status", "ok");
2096 type_status->SetString("value", "Active: " +
2097 ModelSafeGroupToString(routing_info[type]));
2098 } else {
2099 type_status->SetString("status", "warning");
2100 type_status->SetString("value", "Disabled by User");
2103 int live_count = detailed_status.num_entries_by_type[type] -
2104 detailed_status.num_to_delete_entries_by_type[type];
2105 type_status->SetInteger("num_entries",
2106 detailed_status.num_entries_by_type[type]);
2107 type_status->SetInteger("num_live", live_count);
2109 result->Append(type_status.release());
2111 return result.release();
2114 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2115 if (!backend_)
2116 return;
2117 backend_->DeactivateDataType(type);
2120 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2121 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2122 // If the backend isn't running yet, OnBackendInitialized() will call this
2123 // method again after the backend starts up.
2124 if (cached_passphrase_.empty() || !backend_initialized())
2125 return;
2127 // Backend is up and running, so we can consume the cached passphrase.
2128 std::string passphrase = cached_passphrase_;
2129 cached_passphrase_.clear();
2131 // If we need a passphrase to decrypt data, try the cached passphrase.
2132 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2133 if (SetDecryptionPassphrase(passphrase)) {
2134 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2135 return;
2139 // If we get here, we don't have pending keys (or at least, the passphrase
2140 // doesn't decrypt them) - just try to re-encrypt using the encryption
2141 // passphrase.
2142 if (!IsUsingSecondaryPassphrase())
2143 SetEncryptionPassphrase(passphrase, IMPLICIT);
2146 void ProfileSyncService::RequestAccessToken() {
2147 // Only one active request at a time.
2148 if (access_token_request_ != NULL)
2149 return;
2150 request_access_token_retry_timer_.Stop();
2151 OAuth2TokenService::ScopeSet oauth2_scopes;
2152 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2154 // Invalidate previous token, otherwise token service will return the same
2155 // token again.
2156 const std::string& account_id = signin_->GetAccountIdToUse();
2157 if (!access_token_.empty()) {
2158 oauth2_token_service_->InvalidateToken(
2159 account_id, oauth2_scopes, access_token_);
2162 access_token_.clear();
2164 token_request_time_ = base::Time::Now();
2165 token_receive_time_ = base::Time();
2166 next_token_request_time_ = base::Time();
2167 access_token_request_ =
2168 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2171 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2172 PassphraseType type) {
2173 // This should only be called when the backend has been initialized.
2174 DCHECK(backend_initialized());
2175 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2176 "Data is already encrypted using an explicit passphrase";
2177 DCHECK(!(type == EXPLICIT &&
2178 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2179 "Can not set explicit passphrase when decryption is needed.";
2181 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2182 << " passphrase for encryption.";
2183 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2184 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2185 // keys. Hence, as long as we're not trying to do an invalid passphrase
2186 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2187 // will succeed. If for some reason a new encryption key arrives via
2188 // sync later, the SBH will trigger another OnPassphraseRequired().
2189 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2190 NotifyObservers();
2192 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2195 bool ProfileSyncService::SetDecryptionPassphrase(
2196 const std::string& passphrase) {
2197 if (IsPassphraseRequired()) {
2198 DVLOG(1) << "Setting passphrase for decryption.";
2199 return backend_->SetDecryptionPassphrase(passphrase);
2200 } else {
2201 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2202 "IsPassphraseRequired() is false.";
2203 return false;
2207 bool ProfileSyncService::EncryptEverythingAllowed() const {
2208 return encrypt_everything_allowed_;
2211 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2212 DCHECK(allowed || !backend_initialized() || !EncryptEverythingEnabled());
2213 encrypt_everything_allowed_ = allowed;
2216 void ProfileSyncService::EnableEncryptEverything() {
2217 DCHECK(EncryptEverythingAllowed());
2219 // Tests override backend_initialized() to always return true, so we
2220 // must check that instead of |backend_initialized_|.
2221 // TODO(akalin): Fix the above. :/
2222 DCHECK(backend_initialized());
2223 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2224 // problems around cancelling encryption in the background (crbug.com/119649).
2225 if (!encrypt_everything_)
2226 encryption_pending_ = true;
2229 bool ProfileSyncService::encryption_pending() const {
2230 // We may be called during the setup process before we're
2231 // initialized (via IsEncryptedDatatypeEnabled and
2232 // IsPassphraseRequiredForDecryption).
2233 return encryption_pending_;
2236 bool ProfileSyncService::EncryptEverythingEnabled() const {
2237 DCHECK(backend_initialized_);
2238 return encrypt_everything_ || encryption_pending_;
2241 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2242 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2243 // We may be called during the setup process before we're
2244 // initialized. In this case, we default to the sensitive types.
2245 return encrypted_types_;
2248 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2249 if (is_sync_managed) {
2250 DisableForUser();
2251 } else {
2252 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2253 startup_controller_->TryStart();
2257 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2258 const std::string& username,
2259 const std::string& password) {
2260 if (!sync_prefs_.IsStartSuppressed() && !password.empty()) {
2261 cached_passphrase_ = password;
2262 // Try to consume the passphrase we just cached. If the sync backend
2263 // is not running yet, the passphrase will remain cached until the
2264 // backend starts up.
2265 ConsumeCachedPassphraseIfPossible();
2267 #if defined(OS_CHROMEOS)
2268 RefreshSpareBootstrapToken(password);
2269 #endif
2270 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE) {
2271 // Track the fact that we're still waiting for auth to complete.
2272 is_auth_in_progress_ = true;
2276 void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2277 const std::string& username) {
2278 sync_disabled_by_admin_ = false;
2279 DisableForUser();
2281 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2282 need_backup_ = true;
2283 backup_finished_ = false;
2287 void ProfileSyncService::AddObserver(
2288 ProfileSyncServiceBase::Observer* observer) {
2289 observers_.AddObserver(observer);
2292 void ProfileSyncService::RemoveObserver(
2293 ProfileSyncServiceBase::Observer* observer) {
2294 observers_.RemoveObserver(observer);
2297 void ProfileSyncService::AddProtocolEventObserver(
2298 browser_sync::ProtocolEventObserver* observer) {
2299 protocol_event_observers_.AddObserver(observer);
2300 if (HasSyncingBackend()) {
2301 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2305 void ProfileSyncService::RemoveProtocolEventObserver(
2306 browser_sync::ProtocolEventObserver* observer) {
2307 protocol_event_observers_.RemoveObserver(observer);
2308 if (HasSyncingBackend() &&
2309 !protocol_event_observers_.might_have_observers()) {
2310 backend_->DisableProtocolEventForwarding();
2314 void ProfileSyncService::AddTypeDebugInfoObserver(
2315 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2316 type_debug_info_observers_.AddObserver(type_debug_info_observer);
2317 if (type_debug_info_observers_.might_have_observers() &&
2318 backend_initialized_) {
2319 backend_->EnableDirectoryTypeDebugInfoForwarding();
2323 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2324 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2325 type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2326 if (!type_debug_info_observers_.might_have_observers() &&
2327 backend_initialized_) {
2328 backend_->DisableDirectoryTypeDebugInfoForwarding();
2332 void ProfileSyncService::AddPreferenceProvider(
2333 SyncTypePreferenceProvider* provider) {
2334 DCHECK(!HasPreferenceProvider(provider))
2335 << "Providers may only be added once!";
2336 preference_providers_.insert(provider);
2339 void ProfileSyncService::RemovePreferenceProvider(
2340 SyncTypePreferenceProvider* provider) {
2341 DCHECK(HasPreferenceProvider(provider))
2342 << "Only providers that have been added before can be removed!";
2343 preference_providers_.erase(provider);
2346 bool ProfileSyncService::HasPreferenceProvider(
2347 SyncTypePreferenceProvider* provider) const {
2348 return preference_providers_.count(provider) > 0;
2351 namespace {
2353 class GetAllNodesRequestHelper
2354 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2355 public:
2356 GetAllNodesRequestHelper(
2357 syncer::ModelTypeSet requested_types,
2358 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2360 void OnReceivedNodesForTypes(
2361 const std::vector<syncer::ModelType>& types,
2362 ScopedVector<base::ListValue> scoped_node_lists);
2364 private:
2365 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2366 virtual ~GetAllNodesRequestHelper();
2368 scoped_ptr<base::ListValue> result_accumulator_;
2370 syncer::ModelTypeSet awaiting_types_;
2371 base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2374 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2375 syncer::ModelTypeSet requested_types,
2376 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2377 : result_accumulator_(new base::ListValue()),
2378 awaiting_types_(requested_types),
2379 callback_(callback) {}
2381 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2382 if (!awaiting_types_.Empty()) {
2383 DLOG(WARNING)
2384 << "GetAllNodesRequest deleted before request was fulfilled. "
2385 << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2389 // Called when the set of nodes for a type or set of types has been returned.
2391 // The nodes for several types can be returned at the same time by specifying
2392 // their types in the |types| array, and putting their results at the
2393 // correspnding indices in the |scoped_node_lists|.
2394 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2395 const std::vector<syncer::ModelType>& types,
2396 ScopedVector<base::ListValue> scoped_node_lists) {
2397 DCHECK_EQ(types.size(), scoped_node_lists.size());
2399 // Take unsafe ownership of the node list.
2400 std::vector<base::ListValue*> node_lists;
2401 scoped_node_lists.release(&node_lists);
2403 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2404 const ModelType type = types[i];
2405 base::ListValue* node_list = node_lists[i];
2407 // Add these results to our list.
2408 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2409 type_dict->SetString("type", ModelTypeToString(type));
2410 type_dict->Set("nodes", node_list);
2411 result_accumulator_->Append(type_dict.release());
2413 // Remember that this part of the request is satisfied.
2414 awaiting_types_.Remove(type);
2417 if (awaiting_types_.Empty()) {
2418 callback_.Run(result_accumulator_.Pass());
2419 callback_.Reset();
2423 } // namespace
2425 void ProfileSyncService::GetAllNodes(
2426 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2427 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2428 directory_types.PutAll(syncer::ControlTypes());
2429 scoped_refptr<GetAllNodesRequestHelper> helper =
2430 new GetAllNodesRequestHelper(directory_types, callback);
2432 if (!backend_initialized_) {
2433 // If there's no backend available to fulfill the request, handle it here.
2434 ScopedVector<base::ListValue> empty_results;
2435 std::vector<ModelType> type_vector;
2436 for (ModelTypeSet::Iterator it = directory_types.First();
2437 it.Good(); it.Inc()) {
2438 type_vector.push_back(it.Get());
2439 empty_results.push_back(new base::ListValue());
2441 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2442 } else {
2443 backend_->GetAllNodesForTypes(
2444 directory_types,
2445 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2449 bool ProfileSyncService::HasObserver(
2450 const ProfileSyncServiceBase::Observer* observer) const {
2451 return observers_.HasObserver(observer);
2454 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2455 return sync_js_controller_.AsWeakPtr();
2458 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2459 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2462 // static
2463 bool ProfileSyncService::IsSyncEnabled() {
2464 // We have switches::kEnableSync just in case we need to change back to
2465 // sync-disabled-by-default on a platform.
2466 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2467 switches::kDisableSync);
2470 bool ProfileSyncService::IsManaged() const {
2471 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2474 void ProfileSyncService::StopAndSuppress() {
2475 sync_prefs_.SetStartSuppressed(true);
2476 if (HasSyncingBackend()) {
2477 backend_->UnregisterInvalidationIds();
2479 ShutdownImpl(syncer::STOP_SYNC);
2482 bool ProfileSyncService::IsStartSuppressed() const {
2483 return sync_prefs_.IsStartSuppressed();
2486 SigninManagerBase* ProfileSyncService::signin() const {
2487 if (!signin_)
2488 return NULL;
2489 return signin_->GetOriginal();
2492 void ProfileSyncService::UnsuppressAndStart() {
2493 DCHECK(profile_);
2494 sync_prefs_.SetStartSuppressed(false);
2495 DCHECK(!signin_.get() || signin_->GetOriginal()->IsAuthenticated());
2496 startup_controller_->TryStart();
2499 void ProfileSyncService::ReconfigureDatatypeManager() {
2500 // If we haven't initialized yet, don't configure the DTM as it could cause
2501 // association to start before a Directory has even been created.
2502 if (backend_initialized_) {
2503 DCHECK(backend_.get());
2504 ConfigureDataTypeManager();
2505 } else if (HasUnrecoverableError()) {
2506 // There is nothing more to configure. So inform the listeners,
2507 NotifyObservers();
2509 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2510 << "Unrecoverable error.";
2511 } else {
2512 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2513 << "initialized";
2517 syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2518 const {
2519 syncer::ModelTypeSet types;
2520 for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2521 preference_providers_.begin();
2522 it != preference_providers_.end();
2523 ++it) {
2524 types.PutAll((*it)->GetPreferredDataTypes());
2526 return types;
2529 const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2530 const {
2531 return data_type_status_table_;
2534 void ProfileSyncService::OnInternalUnrecoverableError(
2535 const tracked_objects::Location& from_here,
2536 const std::string& message,
2537 bool delete_sync_database,
2538 UnrecoverableErrorReason reason) {
2539 DCHECK(!HasUnrecoverableError());
2540 unrecoverable_error_reason_ = reason;
2541 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2544 syncer::SyncManagerFactory::MANAGER_TYPE
2545 ProfileSyncService::GetManagerType() const {
2546 switch (backend_mode_) {
2547 case SYNC:
2548 return syncer::SyncManagerFactory::NORMAL;
2549 case BACKUP:
2550 return syncer::SyncManagerFactory::BACKUP;
2551 case ROLLBACK:
2552 return syncer::SyncManagerFactory::ROLLBACK;
2553 case IDLE:
2554 NOTREACHED();
2556 return syncer::SyncManagerFactory::NORMAL;
2559 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2560 return request_access_token_retry_timer_.IsRunning();
2563 std::string ProfileSyncService::GetAccessTokenForTest() const {
2564 return access_token_;
2567 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2568 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2571 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2572 return sessions_sync_manager_.get();
2575 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2576 return device_info_sync_service_.get();
2579 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2580 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED),
2581 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2582 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2584 ProfileSyncService::SyncTokenStatus
2585 ProfileSyncService::GetSyncTokenStatus() const {
2586 SyncTokenStatus status;
2587 status.connection_status_update_time = connection_status_update_time_;
2588 status.connection_status = connection_status_;
2589 status.token_request_time = token_request_time_;
2590 status.token_receive_time = token_receive_time_;
2591 status.last_get_token_error = last_get_token_error_;
2592 if (request_access_token_retry_timer_.IsRunning())
2593 status.next_token_request_time = next_token_request_time_;
2594 return status;
2597 void ProfileSyncService::OverrideNetworkResourcesForTest(
2598 scoped_ptr<syncer::NetworkResources> network_resources) {
2599 network_resources_ = network_resources.Pass();
2602 bool ProfileSyncService::HasSyncingBackend() const {
2603 return backend_mode_ != SYNC ? false : backend_ != NULL;
2606 void ProfileSyncService::UpdateFirstSyncTimePref() {
2607 if (signin_->GetEffectiveUsername().empty()) {
2608 // Clear if user's not signed in and rollback is done.
2609 if (backend_mode_ != ROLLBACK)
2610 sync_prefs_.ClearFirstSyncTime();
2611 } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2612 backend_mode_ == SYNC) {
2613 // Set if not set before and it's syncing now.
2614 sync_prefs_.SetFirstSyncTime(base::Time::Now());
2618 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2619 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2620 if (first_sync_time.is_null())
2621 return;
2623 clear_browsing_data_.Run(browsing_data_remover_observer_,
2624 profile_,
2625 first_sync_time,
2626 base::Time::Now());
2629 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2630 BrowsingDataRemover::Observer* observer) {
2631 browsing_data_remover_observer_ = observer;
2634 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2635 base::Callback<void(BrowsingDataRemover::Observer* observer,
2636 Profile*,
2637 base::Time,
2638 base::Time)> c) {
2639 clear_browsing_data_ = c;
2642 GURL ProfileSyncService::GetSyncServiceURL(
2643 const base::CommandLine& command_line) {
2644 // By default, dev, canary, and unbranded Chromium users will go to the
2645 // development servers. Development servers have more features than standard
2646 // sync servers. Users with officially-branded Chrome stable and beta builds
2647 // will go to the standard sync servers.
2648 GURL result(kDevServerUrl);
2650 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
2651 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
2652 channel == chrome::VersionInfo::CHANNEL_BETA) {
2653 result = GURL(kSyncServerUrl);
2656 // Override the sync server URL from the command-line, if sync server
2657 // command-line argument exists.
2658 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
2659 std::string value(command_line.GetSwitchValueASCII(
2660 switches::kSyncServiceURL));
2661 if (!value.empty()) {
2662 GURL custom_sync_url(value);
2663 if (custom_sync_url.is_valid()) {
2664 result = custom_sync_url;
2665 } else {
2666 LOG(WARNING) << "The following sync URL specified at the command-line "
2667 << "is invalid: " << value;
2671 return result;
2674 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2675 DCHECK_EQ(backend_mode_, SYNC);
2677 #if defined(ENABLE_PRE_SYNC_BACKUP)
2678 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
2679 // Check backup once a day.
2680 if (!last_backup_time_ &&
2681 (last_synced_time.is_null() ||
2682 base::Time::Now() - last_synced_time >=
2683 base::TimeDelta::FromDays(1))) {
2684 // If sync thread is set, need to serialize check on sync thread after
2685 // closing backup DB.
2686 if (sync_thread_) {
2687 sync_thread_->message_loop_proxy()->PostTask(
2688 FROM_HERE,
2689 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2690 profile_->GetPath().Append(kSyncBackupDataFolderName),
2691 base::MessageLoopProxy::current(),
2692 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2693 weak_factory_.GetWeakPtr())));
2694 } else {
2695 content::BrowserThread::PostTask(
2696 content::BrowserThread::FILE, FROM_HERE,
2697 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2698 profile_->GetPath().Append(kSyncBackupDataFolderName),
2699 base::MessageLoopProxy::current(),
2700 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2701 weak_factory_.GetWeakPtr())));
2704 #endif
2707 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2708 last_backup_time_.reset(new base::Time(backup_time));
2710 DCHECK(device_info_sync_service_);
2711 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2714 void ProfileSyncService::TryStartSyncAfterBackup() {
2715 startup_controller_->Reset(GetRegisteredDataTypes());
2716 startup_controller_->TryStart();
2719 void ProfileSyncService::CleanUpBackup() {
2720 sync_prefs_.ClearFirstSyncTime();
2721 profile_->GetIOTaskRunner()->PostTask(
2722 FROM_HERE,
2723 base::Bind(base::IgnoreResult(base::DeleteFile),
2724 profile_->GetPath().Append(kSyncBackupDataFolderName),
2725 true));
2728 bool ProfileSyncService::NeedBackup() const {
2729 return need_backup_;
2732 base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2733 return device_info_sync_service_->GetLocalDeviceBackupTime();
2736 void ProfileSyncService::FlushDirectory() const {
2737 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2738 // If sync is not initialized yet, we fail silently.
2739 if (backend_initialized_)
2740 backend_->FlushDirectory();
2743 base::FilePath ProfileSyncService::GetDirectoryPathForTest() const {
2744 return directory_path_;
2747 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2748 if (sync_thread_) {
2749 return sync_thread_->message_loop();
2750 } else if (backend_) {
2751 return backend_->GetSyncLoopForTesting();
2752 } else {
2753 return NULL;
2757 void ProfileSyncService::RemoveClientFromServer() const {
2758 if (!backend_initialized_) return;
2759 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
2760 std::string birthday;
2761 syncer::UserShare* user_share = GetUserShare();
2762 if (user_share && user_share->directory.get()) {
2763 birthday = user_share->directory->store_birthday();
2765 if (!access_token_.empty() && !cache_guid.empty() && !birthday.empty()) {
2766 sync_stopped_reporter_->ReportSyncStopped(
2767 access_token_, cache_guid, birthday);