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"
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/strings/string16.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/threading/thread_restrictions.h"
25 #include "build/build_config.h"
26 #include "chrome/browser/bookmarks/enhanced_bookmarks_features.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"
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.
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.
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.
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");
174 void ClearBrowsingData(BrowsingDataRemover::Observer
* observer
,
178 // BrowsingDataRemover deletes itself when it's done.
179 BrowsingDataRemover
* remover
= BrowsingDataRemover::CreateForRange(
180 profile
, start
, end
);
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
,
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()),
221 sync_prefs_(profile_
->GetPrefs()),
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
),
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(
249 profile_
->GetRequestContext(),
250 browser_sync::SyncStoppedReporter::ResultCallback())),
252 startup_controller_weak_factory_(this) {
253 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
255 startup_controller_
.reset(new browser_sync::StartupController(
257 oauth2_token_service
,
260 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
261 startup_controller_weak_factory_
.GetWeakPtr(),
263 backup_rollback_controller_
.reset(new browser_sync::BackupRollbackController(
266 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
267 startup_controller_weak_factory_
.GetWeakPtr(),
269 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
270 startup_controller_weak_factory_
.GetWeakPtr(),
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())
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_
)
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
314 sync_prefs_
.AddSyncPrefObserver(this);
316 // For now, the only thing we can do through policy is to turn sync off.
322 RegisterAuthNotifications();
324 if (!HasSyncSetupCompleted() || signin_
->GetEffectiveUsername().empty()) {
325 // Clean up in case of previous crash / setup abort / signout.
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());
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());
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();
356 need_backup_
= false;
359 #if defined(ENABLE_PRE_SYNC_BACKUP)
360 if (!running_rollback
&& signin_
->GetEffectiveUsername().empty()) {
364 DCHECK(!running_rollback
);
367 startup_controller_
->Reset(GetRegisteredDataTypes());
368 startup_controller_
->TryStart();
371 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
372 DCHECK(!backend_initialized());
373 if (!HasSyncSetupCompleted())
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();
384 if (GetPreferredDataTypes().Size() > 1)
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
392 if (!keep_everything_synced
->IsDefaultValue())
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() {
404 backend_
->StartSyncingWithServer();
407 void ProfileSyncService::RegisterAuthNotifications() {
408 oauth2_token_service_
->AddObserver(this);
410 signin()->AddObserver(this);
413 void ProfileSyncService::UnregisterAuthNotifications() {
415 signin()->RemoveObserver(this);
416 oauth2_token_service_
->RemoveObserver(this);
419 void ProfileSyncService::RegisterDataTypeController(
420 DataTypeController
* data_type_controller
) {
422 directory_data_type_controllers_
.count(data_type_controller
->type()),
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
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()) {
455 return iter
->second
->state() == DataTypeController::RUNNING
;
458 browser_sync::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
459 if (!IsDataTypeControllerRunning(syncer::SESSIONS
))
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()
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();
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());
508 bool ProfileSyncService::ShouldDeleteSyncFolder() {
509 switch (backend_mode_
) {
511 return !HasSyncSetupCompleted();
523 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
529 SyncCredentials credentials
= GetCredentials();
531 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
532 profile_
->GetRequestContext());
534 if (backend_mode_
== SYNC
&& delete_stale_data
)
537 scoped_ptr
<syncer::UnrecoverableErrorHandler
>
538 backend_unrecoverable_error_handler(
539 new browser_sync::BackendUnrecoverableErrorHandler(
540 MakeWeakHandle(weak_factory_
.GetWeakPtr())));
542 backend_
->Initialize(
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())
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.";
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.";
613 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
616 void ProfileSyncService::StartUpSlowBackendComponents(
617 ProfileSyncService::BackendMode mode
) {
618 DCHECK_NE(IDLE
, mode
);
619 if (backend_mode_
== mode
) {
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
;
638 if (backend_mode_
== ROLLBACK
||
639 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
640 // Wait for rollback/backup to finish before start new backend.
644 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
645 if (backend_mode_
!= BACKUP
)
646 backup_rollback_controller_
->StartBackup();
650 DVLOG(1) << "Start backend mode: " << mode
;
654 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
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(
685 invalidator
= provider
->GetInvalidationService();
688 directory_path_
= profile_
->GetPath().Append(sync_folder
);
691 factory_
->CreateSyncBackendHost(
692 profile_
->GetDebugName(),
695 sync_prefs_
.AsWeakPtr(),
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
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",
723 if (HasSyncingBackend())
724 backend_
->UpdateCredentials(GetCredentials());
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(
747 request_access_token_backoff_
.GetTimeUntilRelease(),
748 base::Bind(&ProfileSyncService::RequestAccessToken
,
749 weak_factory_
.GetWeakPtr()));
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
,
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 if (account_id
== signin_
->GetAccountIdToUse())
775 OnRefreshTokensLoaded();
778 void ProfileSyncService::OnRefreshTokenRevoked(
779 const std::string
& account_id
) {
780 if (!IsOAuthRefreshTokenAvailable()) {
781 access_token_
.clear();
782 // The additional check around IsOAuthRefreshTokenAvailable() above
783 // prevents us sounding the alarm if we actually have a valid token but
784 // a refresh attempt failed for any variety of reasons
785 // (e.g. flaky network). It's possible the token we do have is also
786 // invalid, but in that case we should already have (or can expect) an
787 // auth error sent from the sync backend.
788 UpdateAuthErrorState(
789 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
793 void ProfileSyncService::OnRefreshTokensLoaded() {
794 // This notification gets fired when OAuth2TokenService loads the tokens
796 // Initialize the backend if sync is enabled. If the sync token was
797 // not loaded, GetCredentials() will generate invalid credentials to
798 // cause the backend to generate an auth error (crbug.com/121755).
799 if (HasSyncingBackend()) {
800 RequestAccessToken();
802 startup_controller_
->TryStart();
806 void ProfileSyncService::Shutdown() {
807 UnregisterAuthNotifications();
809 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
810 if (sync_error_controller_
) {
811 // Destroy the SyncErrorController when the service shuts down for good.
812 RemoveObserver(sync_error_controller_
.get());
813 sync_error_controller_
.reset();
817 sync_thread_
->Stop();
820 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
822 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
823 // If the backend is already shut down when a DISABLE_SYNC happens,
824 // the data directory needs to be cleaned up here.
825 sync_thread_
->message_loop()->PostTask(FROM_HERE
,
826 base::Bind(&DeleteSyncDataFolder
, directory_path_
));
831 if (reason
== syncer::ShutdownReason::STOP_SYNC
832 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
833 RemoveClientFromServer();
836 non_blocking_data_type_manager_
.DisconnectSyncBackend();
838 // First, we spin down the backend to stop change processing as soon as
840 base::Time shutdown_start_time
= base::Time::Now();
841 backend_
->StopSyncingForShutdown();
843 // Stop all data type controllers, if needed. Note that until Stop
844 // completes, it is possible in theory to have a ChangeProcessor apply a
845 // change from a native model. In that case, it will get applied to the sync
846 // database (which doesn't get destroyed until we destroy the backend below)
847 // as an unsynced change. That will be persisted, and committed on restart.
848 if (directory_data_type_manager_
) {
849 if (directory_data_type_manager_
->state() != DataTypeManager::STOPPED
) {
850 // When aborting as part of shutdown, we should expect an aborted sync
851 // configure result, else we'll dcheck when we try to read the sync error.
852 expect_sync_configuration_aborted_
= true;
853 directory_data_type_manager_
->Stop();
855 directory_data_type_manager_
.reset();
858 // Shutdown the migrator before the backend to ensure it doesn't pull a null
861 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
863 // Move aside the backend so nobody else tries to use it while we are
865 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
866 if (doomed_backend
) {
867 sync_thread_
= doomed_backend
->Shutdown(reason
);
868 doomed_backend
.reset();
870 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
871 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
873 weak_factory_
.InvalidateWeakPtrs();
875 if (backend_mode_
== SYNC
)
876 startup_controller_
->Reset(GetRegisteredDataTypes());
878 // Don't let backup block sync regardless backup succeeded or not.
879 if (backend_mode_
== BACKUP
)
880 backup_finished_
= true;
882 // Sync could be blocked by rollback/backup. Post task to check whether sync
883 // should start after shutting down rollback/backup backend.
884 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
885 reason
!= syncer::SWITCH_MODE_SYNC
&&
886 reason
!= syncer::BROWSER_SHUTDOWN
) {
887 base::MessageLoop::current()->PostTask(
888 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
889 startup_controller_weak_factory_
.GetWeakPtr()));
892 // Clear various flags.
893 backend_mode_
= IDLE
;
894 expect_sync_configuration_aborted_
= false;
895 is_auth_in_progress_
= false;
896 backend_initialized_
= false;
897 cached_passphrase_
.clear();
898 encryption_pending_
= false;
899 encrypt_everything_
= false;
900 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
901 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
902 request_access_token_retry_timer_
.Stop();
903 // Revert to "no auth error".
904 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
905 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
910 void ProfileSyncService::DisableForUser() {
911 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
912 // PSS clients don't think we're set up while we're shutting down.
913 sync_prefs_
.ClearPreferences();
914 ClearUnrecoverableError();
915 ShutdownImpl(syncer::DISABLE_SYNC
);
918 bool ProfileSyncService::HasSyncSetupCompleted() const {
919 return sync_prefs_
.HasSyncSetupCompleted();
922 void ProfileSyncService::SetSyncSetupCompleted() {
923 sync_prefs_
.SetSyncSetupCompleted();
926 void ProfileSyncService::UpdateLastSyncedTime() {
927 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
930 void ProfileSyncService::NotifyObservers() {
931 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer
, observers_
,
935 void ProfileSyncService::NotifySyncCycleCompleted() {
936 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer
, observers_
,
937 OnSyncCycleCompleted());
940 void ProfileSyncService::ClearStaleErrors() {
941 ClearUnrecoverableError();
942 last_actionable_error_
= SyncProtocolError();
943 // Clear the data type errors as well.
944 if (directory_data_type_manager_
.get())
945 directory_data_type_manager_
->ResetDataTypeErrors();
949 void ProfileSyncService::ClearUnrecoverableError() {
950 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
951 unrecoverable_error_message_
.clear();
952 unrecoverable_error_location_
= tracked_objects::Location();
955 void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type
) {
956 if (directory_data_type_controllers_
.count(data_type
) > 0)
961 // An invariant has been violated. Transition to an error state where we try
962 // to do as little work as possible, to avoid further corruption or crashes.
963 void ProfileSyncService::OnUnrecoverableError(
964 const tracked_objects::Location
& from_here
,
965 const std::string
& message
) {
966 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
967 // interface are assumed to originate within the syncer.
968 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
969 OnUnrecoverableErrorImpl(from_here
, message
, true);
972 void ProfileSyncService::OnUnrecoverableErrorImpl(
973 const tracked_objects::Location
& from_here
,
974 const std::string
& message
,
975 bool delete_sync_database
) {
976 DCHECK(HasUnrecoverableError());
977 unrecoverable_error_message_
= message
;
978 unrecoverable_error_location_
= from_here
;
980 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
981 unrecoverable_error_reason_
,
983 std::string location
;
984 from_here
.Write(true, true, &location
);
986 << "Unrecoverable error detected at " << location
987 << " -- ProfileSyncService unusable: " << message
;
989 // Shut all data types down.
990 base::MessageLoop::current()->PostTask(FROM_HERE
,
991 base::Bind(&ProfileSyncService::ShutdownImpl
,
992 weak_factory_
.GetWeakPtr(),
993 delete_sync_database
?
994 syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
997 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
998 DCHECK(backend_initialized_
);
999 directory_data_type_manager_
->ReenableType(type
);
1002 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1003 if (backend_mode_
!= SYNC
)
1006 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1008 if (is_first_time_sync_configure_
) {
1009 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1011 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1014 base::Time on_backend_initialized_time
= base::Time::Now();
1015 base::TimeDelta delta
= on_backend_initialized_time
-
1016 startup_controller_
->start_backend_time();
1017 if (is_first_time_sync_configure_
) {
1018 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1020 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1024 void ProfileSyncService::PostBackendInitialization() {
1025 // Never get here for backup / restore.
1026 DCHECK_EQ(backend_mode_
, SYNC
);
1028 if (last_backup_time_
) {
1029 DCHECK(device_info_sync_service_
);
1030 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1033 if (protocol_event_observers_
.might_have_observers()) {
1034 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1037 non_blocking_data_type_manager_
.ConnectSyncBackend(
1038 backend_
->GetSyncContextProxy());
1040 if (type_debug_info_observers_
.might_have_observers()) {
1041 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1044 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1045 // backend is initialized. We want to call this before notifying observers in
1046 // case this operation affects the "passphrase required" status.
1047 ConsumeCachedPassphraseIfPossible();
1049 // The very first time the backend initializes is effectively the first time
1050 // we can say we successfully "synced". LastSyncedTime will only be null in
1051 // this case, because the pref wasn't restored on StartUp.
1052 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1053 UpdateLastSyncedTime();
1056 if (startup_controller_
->auto_start_enabled() && !FirstSetupInProgress()) {
1057 // Backend is initialized but we're not in sync setup, so this must be an
1058 // autostart - mark our sync setup as completed and we'll start syncing
1060 SetSyncSetupCompleted();
1063 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1064 // data type configuration because observer may flag setup as complete and
1065 // trigger data type configuration.
1066 if (HasSyncSetupCompleted()) {
1067 ConfigureDataTypeManager();
1069 DCHECK(FirstSetupInProgress());
1075 void ProfileSyncService::OnBackendInitialized(
1076 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1077 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1078 debug_info_listener
,
1079 const std::string
& cache_guid
,
1081 UpdateBackendInitUMA(success
);
1084 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1085 // and surface error UI to alert the user sync has stopped.
1086 // Keep the directory around for now so that on restart we will retry
1087 // again and potentially succeed in presence of transient file IO failures
1088 // or permissions issues, etc.
1090 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1091 // Unlike every other UnrecoverableError, it does not delete our sync data.
1092 // This exception made sense at the time it was implemented, but our new
1093 // directory corruption recovery mechanism makes it obsolete. By the time
1094 // we get here, we will have already tried and failed to delete the
1095 // directory. It would be no big deal if we tried to delete it again.
1096 OnInternalUnrecoverableError(FROM_HERE
,
1097 "BackendInitialize failure",
1099 ERROR_REASON_BACKEND_INIT_FAILURE
);
1103 backend_initialized_
= true;
1105 sync_js_controller_
.AttachJsBackend(js_backend
);
1106 debug_info_listener_
= debug_info_listener
;
1108 SigninClient
* signin_client
=
1109 ChromeSigninClientFactory::GetForProfile(profile_
);
1110 DCHECK(signin_client
);
1111 std::string signin_scoped_device_id
=
1112 signin_client
->GetSigninScopedDeviceId();
1114 // Initialize local device info.
1115 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1117 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1118 non_blocking_data_type_manager_
.SetPreferredTypes(GetPreferredDataTypes());
1120 // Give the DataTypeControllers a handle to the now initialized backend
1122 for (DataTypeController::TypeMap::iterator it
=
1123 directory_data_type_controllers_
.begin();
1124 it
!= directory_data_type_controllers_
.end(); ++it
) {
1125 it
->second
->OnUserShareReady(GetUserShare());
1128 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1129 ConfigureDataTypeManager();
1131 PostBackendInitialization();
1134 void ProfileSyncService::OnSyncCycleCompleted() {
1135 UpdateLastSyncedTime();
1136 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1137 // Trigger garbage collection of old sessions now that we've downloaded
1138 // any new session data.
1139 base::MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
1140 &SessionsSyncManager::DoGarbageCollection
,
1141 base::AsWeakPtr(sessions_sync_manager_
.get())));
1143 DVLOG(2) << "Notifying observers sync cycle completed";
1144 NotifySyncCycleCompleted();
1147 void ProfileSyncService::OnExperimentsChanged(
1148 const syncer::Experiments
& experiments
) {
1149 if (current_experiments_
.Matches(experiments
))
1152 current_experiments_
= experiments
;
1154 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1155 experiments
.gcm_invalidations_enabled
);
1156 profile()->GetPrefs()->SetBoolean(
1157 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1158 experiments
.wallet_sync_enabled
);
1160 if (experiments
.enhanced_bookmarks_enabled
) {
1161 profile_
->GetPrefs()->SetString(
1162 sync_driver::prefs::kEnhancedBookmarksExtensionId
,
1163 experiments
.enhanced_bookmarks_ext_id
);
1165 profile_
->GetPrefs()->ClearPref(
1166 sync_driver::prefs::kEnhancedBookmarksExtensionId
);
1168 UpdateBookmarksExperimentState(
1169 profile_
->GetPrefs(), g_browser_process
->local_state(), true,
1170 experiments
.enhanced_bookmarks_enabled
? BOOKMARKS_EXPERIMENT_ENABLED
:
1171 BOOKMARKS_EXPERIMENT_NONE
);
1173 // If this is a first time sync for a client, this will be called before
1174 // OnBackendInitialized() to ensure the new datatypes are available at sync
1175 // setup. As a result, the migrator won't exist yet. This is fine because for
1176 // first time sync cases we're only concerned with making the datatype
1178 if (migrator_
.get() &&
1179 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1180 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy.";
1184 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1185 syncer::ModelTypeSet to_add
;
1186 const syncer::ModelTypeSet to_register
=
1187 Difference(to_add
, registered_types
);
1188 DVLOG(2) << "OnExperimentsChanged called with types: "
1189 << syncer::ModelTypeSetToString(to_add
);
1190 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register
);
1192 for (syncer::ModelTypeSet::Iterator it
= to_register
.First();
1193 it
.Good(); it
.Inc()) {
1194 // Received notice to enable experimental type. Check if the type is
1195 // registered, and if not register a new datatype controller.
1196 RegisterNewDataType(it
.Get());
1199 // Check if the user has "Keep Everything Synced" enabled. If so, we want
1200 // to turn on all experimental types if they're not already on. Otherwise we
1202 // Note: if any types are already registered, we don't turn them on. This
1203 // covers the case where we're already in the process of reconfiguring
1204 // to turn an experimental type on.
1205 if (sync_prefs_
.HasKeepEverythingSynced()) {
1206 // Mark all data types as preferred.
1207 sync_prefs_
.SetPreferredDataTypes(registered_types
, registered_types
);
1209 // Only automatically turn on types if we have already finished set up.
1210 // Otherwise, just leave the experimental types on by default.
1211 if (!to_register
.Empty() && HasSyncSetupCompleted() && migrator_
) {
1212 DVLOG(1) << "Dynamically enabling new datatypes: "
1213 << syncer::ModelTypeSetToString(to_register
);
1214 OnMigrationNeededForTypes(to_register
);
1219 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1220 is_auth_in_progress_
= false;
1221 last_auth_error_
= error
;
1228 AuthError
ConnectionStatusToAuthError(
1229 syncer::ConnectionStatus status
) {
1231 case syncer::CONNECTION_OK
:
1232 return AuthError::AuthErrorNone();
1234 case syncer::CONNECTION_AUTH_ERROR
:
1235 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1237 case syncer::CONNECTION_SERVER_ERROR
:
1238 return AuthError(AuthError::CONNECTION_FAILED
);
1242 return AuthError(AuthError::CONNECTION_FAILED
);
1248 void ProfileSyncService::OnConnectionStatusChange(
1249 syncer::ConnectionStatus status
) {
1250 connection_status_update_time_
= base::Time::Now();
1251 connection_status_
= status
;
1252 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1253 // Sync server returned error indicating that access token is invalid. It
1254 // could be either expired or access is revoked. Let's request another
1255 // access token and if access is revoked then request for token will fail
1256 // with corresponding error. If access token is repeatedly reported
1257 // invalid, there may be some issues with server, e.g. authentication
1258 // state is inconsistent on sync and token server. In that case, we
1259 // backoff token requests exponentially to avoid hammering token server
1260 // too much and to avoid getting same token due to token server's caching
1261 // policy. |request_access_token_retry_timer_| is used to backoff request
1262 // triggered by both auth error and failure talking to GAIA server.
1263 // Therefore, we're likely to reach the backoff ceiling more quickly than
1264 // you would expect from looking at the BackoffPolicy if both types of
1265 // errors happen. We shouldn't receive two errors back-to-back without
1266 // attempting a token/sync request in between, thus crank up request delay
1267 // unnecessary. This is because we won't make a sync request if we hit an
1268 // error until GAIA succeeds at sending a new token, and we won't request
1269 // a new token unless sync reports a token failure. But to be safe, don't
1270 // schedule request if this happens.
1271 if (request_access_token_retry_timer_
.IsRunning()) {
1272 // The timer to perform a request later is already running; nothing
1273 // further needs to be done at this point.
1274 } else if (request_access_token_backoff_
.failure_count() == 0) {
1275 // First time request without delay. Currently invalid token is used
1276 // to initialize sync backend and we'll always end up here. We don't
1277 // want to delay initialization.
1278 request_access_token_backoff_
.InformOfRequest(false);
1279 RequestAccessToken();
1281 request_access_token_backoff_
.InformOfRequest(false);
1282 request_access_token_retry_timer_
.Start(
1284 request_access_token_backoff_
.GetTimeUntilRelease(),
1285 base::Bind(&ProfileSyncService::RequestAccessToken
,
1286 weak_factory_
.GetWeakPtr()));
1289 // Reset backoff time after successful connection.
1290 if (status
== syncer::CONNECTION_OK
) {
1291 // Request shouldn't be scheduled at this time. But if it is, it's
1292 // possible that sync flips between OK and auth error states rapidly,
1293 // thus hammers token server. To be safe, only reset backoff delay when
1294 // no scheduled request.
1295 if (request_access_token_retry_timer_
.IsRunning()) {
1298 request_access_token_backoff_
.Reset();
1302 const GoogleServiceAuthError auth_error
=
1303 ConnectionStatusToAuthError(status
);
1304 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1305 UpdateAuthErrorState(auth_error
);
1309 void ProfileSyncService::StopSyncingPermanently() {
1310 sync_prefs_
.SetStartSuppressed(true);
1314 void ProfileSyncService::OnPassphraseRequired(
1315 syncer::PassphraseRequiredReason reason
,
1316 const sync_pb::EncryptedData
& pending_keys
) {
1317 DCHECK(backend_
.get());
1318 DCHECK(backend_
->IsNigoriEnabled());
1320 // TODO(lipalani) : add this check to other locations as well.
1321 if (HasUnrecoverableError()) {
1322 // When unrecoverable error is detected we post a task to shutdown the
1323 // backend. The task might not have executed yet.
1327 DVLOG(1) << "Passphrase required with reason: "
1328 << syncer::PassphraseRequiredReasonToString(reason
);
1329 passphrase_required_reason_
= reason
;
1331 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1332 if (directory_data_type_manager_
) {
1333 // Reconfigure without the encrypted types (excluded implicitly via the
1334 // failed datatypes handler).
1335 directory_data_type_manager_
->Configure(types
,
1336 syncer::CONFIGURE_REASON_CRYPTO
);
1339 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1341 // Notify observers that the passphrase status may have changed.
1345 void ProfileSyncService::OnPassphraseAccepted() {
1346 DVLOG(1) << "Received OnPassphraseAccepted.";
1348 // If the pending keys were resolved via keystore, it's possible we never
1349 // consumed our cached passphrase. Clear it now.
1350 if (!cached_passphrase_
.empty())
1351 cached_passphrase_
.clear();
1353 // Reset passphrase_required_reason_ since we know we no longer require the
1354 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1355 // because that can be called by OnPassphraseRequired() if no encrypted data
1356 // types are enabled, and we don't want to clobber the true passphrase error.
1357 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1359 // Make sure the data types that depend on the passphrase are started at
1361 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1362 if (directory_data_type_manager_
) {
1363 // Re-enable any encrypted types if necessary.
1364 directory_data_type_manager_
->Configure(types
,
1365 syncer::CONFIGURE_REASON_CRYPTO
);
1368 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1373 void ProfileSyncService::OnEncryptedTypesChanged(
1374 syncer::ModelTypeSet encrypted_types
,
1375 bool encrypt_everything
) {
1376 encrypted_types_
= encrypted_types
;
1377 encrypt_everything_
= encrypt_everything
;
1378 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1379 DVLOG(1) << "Encrypted types changed to "
1380 << syncer::ModelTypeSetToString(encrypted_types_
)
1381 << " (encrypt everything is set to "
1382 << (encrypt_everything_
? "true" : "false") << ")";
1383 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1388 void ProfileSyncService::OnEncryptionComplete() {
1389 DVLOG(1) << "Encryption complete";
1390 if (encryption_pending_
&& encrypt_everything_
) {
1391 encryption_pending_
= false;
1392 // This is to nudge the integration tests when encryption is
1398 void ProfileSyncService::OnMigrationNeededForTypes(
1399 syncer::ModelTypeSet types
) {
1400 DCHECK(backend_initialized_
);
1401 DCHECK(directory_data_type_manager_
.get());
1403 // Migrator must be valid, because we don't sync until it is created and this
1404 // callback originates from a sync cycle.
1405 migrator_
->MigrateTypes(types
);
1408 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1409 last_actionable_error_
= error
;
1410 DCHECK_NE(last_actionable_error_
.action
,
1411 syncer::UNKNOWN_ACTION
);
1412 switch (error
.action
) {
1413 case syncer::UPGRADE_CLIENT
:
1414 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1415 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1416 case syncer::STOP_AND_RESTART_SYNC
:
1417 // TODO(lipalani) : if setup in progress we want to display these
1418 // actions in the popup. The current experience might not be optimal for
1419 // the user. We just dismiss the dialog.
1420 if (startup_controller_
->setup_in_progress()) {
1421 StopSyncingPermanently();
1422 expect_sync_configuration_aborted_
= true;
1424 // Trigger an unrecoverable error to stop syncing.
1425 OnInternalUnrecoverableError(FROM_HERE
,
1426 last_actionable_error_
.error_description
,
1428 ERROR_REASON_ACTIONABLE_ERROR
);
1430 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1431 backup_rollback_controller_
->OnRollbackReceived();
1432 // Fall through to shutdown backend and sign user out.
1433 case syncer::DISABLE_SYNC_ON_CLIENT
:
1434 StopSyncingPermanently();
1435 #if !defined(OS_CHROMEOS)
1436 // On desktop Chrome, sign out the user after a dashboard clear.
1437 // Skip sign out on ChromeOS/Android.
1438 if (!startup_controller_
->auto_start_enabled()) {
1439 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1440 signin_metrics::SERVER_FORCED_DISABLE
);
1444 case syncer::ROLLBACK_DONE
:
1445 backup_rollback_controller_
->OnRollbackDone();
1447 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1448 // Sync disabled by domain admin. we should stop syncing until next
1450 sync_disabled_by_admin_
= true;
1451 ShutdownImpl(syncer::DISABLE_SYNC
);
1458 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1459 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1460 !backup_rollback_controller_
->StartRollback())) {
1461 // Clean up backup data for sign-out only or when rollback is disabled.
1463 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1464 // Shut down ROLLBACK backend and delete backup DB.
1465 ShutdownImpl(syncer::DISABLE_SYNC
);
1466 sync_prefs_
.ClearFirstSyncTime();
1470 void ProfileSyncService::OnConfigureDone(
1471 const DataTypeManager::ConfigureResult
& result
) {
1472 configure_status_
= result
.status
;
1473 data_type_status_table_
= result
.data_type_status_table
;
1475 if (backend_mode_
!= SYNC
) {
1476 if (configure_status_
== DataTypeManager::OK
) {
1477 StartSyncingWithServer();
1479 // Backup is done after models are associated.
1480 if (backend_mode_
== BACKUP
)
1481 backup_finished_
= true;
1483 // Asynchronously check whether sync needs to start.
1484 base::MessageLoop::current()->PostTask(
1485 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1486 startup_controller_weak_factory_
.GetWeakPtr()));
1487 } else if (!expect_sync_configuration_aborted_
) {
1488 DVLOG(1) << "Backup/rollback backend failed to configure.";
1489 ShutdownImpl(syncer::STOP_SYNC
);
1495 // We should have cleared our cached passphrase before we get here (in
1496 // OnBackendInitialized()).
1497 DCHECK(cached_passphrase_
.empty());
1499 if (!sync_configure_start_time_
.is_null()) {
1500 if (result
.status
== DataTypeManager::OK
) {
1501 base::Time sync_configure_stop_time
= base::Time::Now();
1502 base::TimeDelta delta
= sync_configure_stop_time
-
1503 sync_configure_start_time_
;
1504 if (is_first_time_sync_configure_
) {
1505 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1507 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1511 sync_configure_start_time_
= base::Time();
1514 // Notify listeners that configuration is done.
1515 content::NotificationService::current()->Notify(
1516 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1517 content::Source
<ProfileSyncService
>(this),
1518 content::NotificationService::NoDetails());
1520 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1521 // The possible status values:
1522 // ABORT - Configuration was aborted. This is not an error, if
1523 // initiated by user.
1524 // OK - Some or all types succeeded.
1525 // Everything else is an UnrecoverableError. So treat it as such.
1527 // First handle the abort case.
1528 if (configure_status_
== DataTypeManager::ABORTED
&&
1529 expect_sync_configuration_aborted_
) {
1530 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1531 expect_sync_configuration_aborted_
= false;
1535 // Handle unrecoverable error.
1536 if (configure_status_
!= DataTypeManager::OK
) {
1537 // Something catastrophic had happened. We should only have one
1538 // error representing it.
1539 syncer::SyncError error
=
1540 data_type_status_table_
.GetUnrecoverableError();
1541 DCHECK(error
.IsSet());
1542 std::string message
=
1543 "Sync configuration failed with status " +
1544 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1546 syncer::ModelTypeSetToString(
1547 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1548 ": " + error
.message();
1549 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1550 OnInternalUnrecoverableError(error
.location(),
1553 ERROR_REASON_CONFIGURATION_FAILURE
);
1557 // We should never get in a state where we have no encrypted datatypes
1558 // enabled, and yet we still think we require a passphrase for decryption.
1559 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1560 !IsEncryptedDatatypeEnabled()));
1562 // This must be done before we start syncing with the server to avoid
1563 // sending unencrypted data up on a first time sync.
1564 if (encryption_pending_
)
1565 backend_
->EnableEncryptEverything();
1568 if (migrator_
.get() &&
1569 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1570 // Migration in progress. Let the migrator know we just finished
1571 // configuring something. It will be up to the migrator to call
1572 // StartSyncingWithServer() if migration is now finished.
1573 migrator_
->OnConfigureDone(result
);
1575 StartSyncingWithServer();
1579 void ProfileSyncService::OnConfigureStart() {
1580 sync_configure_start_time_
= base::Time::Now();
1584 ProfileSyncService::SyncStatusSummary
1585 ProfileSyncService::QuerySyncStatusSummary() {
1586 if (HasUnrecoverableError()) {
1587 return UNRECOVERABLE_ERROR
;
1588 } else if (!backend_
) {
1590 } else if (backend_mode_
== BACKUP
) {
1591 return BACKUP_USER_DATA
;
1592 } else if (backend_mode_
== ROLLBACK
) {
1593 return ROLLBACK_USER_DATA
;
1594 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1595 return SETUP_INCOMPLETE
;
1597 backend_
.get() && HasSyncSetupCompleted() &&
1598 directory_data_type_manager_
.get() &&
1599 directory_data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1600 return DATATYPES_NOT_INITIALIZED
;
1601 } else if (SyncActive()) {
1604 return UNKNOWN_ERROR
;
1607 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1608 SyncStatusSummary status
= QuerySyncStatusSummary();
1610 std::string config_status_str
=
1611 configure_status_
!= DataTypeManager::UNKNOWN
?
1612 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1615 case UNRECOVERABLE_ERROR
:
1616 return "Unrecoverable error detected";
1618 return "Syncing not enabled";
1619 case SETUP_INCOMPLETE
:
1620 return "First time sync setup incomplete";
1621 case DATATYPES_NOT_INITIALIZED
:
1622 return "Datatypes not fully initialized";
1624 return "Sync service initialized";
1625 case BACKUP_USER_DATA
:
1626 return "Backing-up user data. Status: " + config_status_str
;
1627 case ROLLBACK_USER_DATA
:
1628 return "Restoring user data. Status: " + config_status_str
;
1630 return "Status unknown: Internal error?";
1634 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1635 return startup_controller_
->GetBackendInitializationStateString();
1638 bool ProfileSyncService::auto_start_enabled() const {
1639 return startup_controller_
->auto_start_enabled();
1642 bool ProfileSyncService::setup_in_progress() const {
1643 return startup_controller_
->setup_in_progress();
1646 bool ProfileSyncService::QueryDetailedSyncStatus(
1647 SyncBackendHost::Status
* result
) {
1648 if (backend_
.get() && backend_initialized_
) {
1649 *result
= backend_
->GetDetailedStatus();
1652 SyncBackendHost::Status status
;
1653 status
.sync_protocol_error
= last_actionable_error_
;
1659 const AuthError
& ProfileSyncService::GetAuthError() const {
1660 return last_auth_error_
;
1663 bool ProfileSyncService::FirstSetupInProgress() const {
1664 return !HasSyncSetupCompleted() && startup_controller_
->setup_in_progress();
1667 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1668 // This method is a no-op if |setup_in_progress_| remains unchanged.
1669 if (startup_controller_
->setup_in_progress() == setup_in_progress
)
1672 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1673 if (!setup_in_progress
&& backend_initialized())
1674 ReconfigureDatatypeManager();
1678 bool ProfileSyncService::SyncActive() const {
1679 return backend_initialized_
&& backend_mode_
== SYNC
&&
1680 directory_data_type_manager_
&&
1681 directory_data_type_manager_
->state() != DataTypeManager::STOPPED
;
1684 bool ProfileSyncService::backend_initialized() const {
1685 return backend_initialized_
;
1688 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1689 return backend_mode_
;
1692 bool ProfileSyncService::ConfigurationDone() const {
1693 return directory_data_type_manager_
&&
1694 directory_data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1697 bool ProfileSyncService::waiting_for_auth() const {
1698 return is_auth_in_progress_
;
1701 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1702 return current_experiments_
;
1705 bool ProfileSyncService::HasUnrecoverableError() const {
1706 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1709 bool ProfileSyncService::IsPassphraseRequired() const {
1710 return passphrase_required_reason_
!=
1711 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1714 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1715 // If there is an encrypted datatype enabled and we don't have the proper
1716 // passphrase, we must prompt the user for a passphrase. The only way for the
1717 // user to avoid entering their passphrase is to disable the encrypted types.
1718 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1721 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1722 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1723 if (last_synced_time
.is_null())
1724 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1726 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1728 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1729 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1731 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1732 ui::TimeFormat::LENGTH_SHORT
,
1733 time_since_last_sync
);
1736 void ProfileSyncService::UpdateSelectedTypesHistogram(
1737 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1738 if (!HasSyncSetupCompleted() ||
1739 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1740 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1743 // Only log the data types that are shown in the sync settings ui.
1744 // Note: the order of these types must match the ordering of
1745 // the respective types in ModelType
1746 const sync_driver::user_selectable_type::UserSelectableSyncType
1747 user_selectable_types
[] = {
1748 sync_driver::user_selectable_type::BOOKMARKS
,
1749 sync_driver::user_selectable_type::PREFERENCES
,
1750 sync_driver::user_selectable_type::PASSWORDS
,
1751 sync_driver::user_selectable_type::AUTOFILL
,
1752 sync_driver::user_selectable_type::THEMES
,
1753 sync_driver::user_selectable_type::TYPED_URLS
,
1754 sync_driver::user_selectable_type::EXTENSIONS
,
1755 sync_driver::user_selectable_type::APPS
,
1756 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1757 sync_driver::user_selectable_type::PROXY_TABS
,
1760 static_assert(35 == syncer::MODEL_TYPE_COUNT
,
1761 "custom config histogram must be updated");
1763 if (!sync_everything
) {
1764 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1766 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1767 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1769 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1771 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1773 const syncer::ModelType type
= it
.Get();
1774 if (chosen_types
.Has(type
) &&
1775 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1776 // Selected type has changed - log it.
1777 UMA_HISTOGRAM_ENUMERATION(
1779 user_selectable_types
[i
],
1780 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1786 #if defined(OS_CHROMEOS)
1787 void ProfileSyncService::RefreshSpareBootstrapToken(
1788 const std::string
& passphrase
) {
1789 sync_driver::SystemEncryptor encryptor
;
1790 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1791 // The first 2 params (hostname and username) doesn't have any effect here.
1792 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1794 std::string bootstrap_token
;
1795 if (!temp_cryptographer
.AddKey(key_params
)) {
1796 NOTREACHED() << "Failed to add key to cryptographer.";
1798 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1799 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1803 void ProfileSyncService::OnUserChoseDatatypes(
1804 bool sync_everything
,
1805 syncer::ModelTypeSet chosen_types
) {
1806 if (!backend_
.get() && !HasUnrecoverableError()) {
1811 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1812 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1814 if (directory_data_type_manager_
.get())
1815 directory_data_type_manager_
->ResetDataTypeErrors();
1816 ChangePreferredDataTypes(chosen_types
);
1817 AcknowledgeSyncedTypes();
1820 void ProfileSyncService::ChangePreferredDataTypes(
1821 syncer::ModelTypeSet preferred_types
) {
1823 DVLOG(1) << "ChangePreferredDataTypes invoked";
1824 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1825 const syncer::ModelTypeSet registered_preferred_types
=
1826 Intersection(registered_types
, preferred_types
);
1827 sync_prefs_
.SetPreferredDataTypes(registered_types
,
1828 registered_preferred_types
);
1830 // Now reconfigure the DTM.
1831 ReconfigureDatatypeManager();
1833 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1834 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1835 // which types should be enabled and when.
1838 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1839 if (!SyncActive() || !ConfigurationDone())
1840 return syncer::ModelTypeSet();
1841 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1842 const syncer::ModelTypeSet failed_types
=
1843 data_type_status_table_
.GetFailedTypes();
1844 return Difference(preferred_types
, failed_types
);
1847 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1848 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1849 const syncer::ModelTypeSet preferred_types
=
1850 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1851 const syncer::ModelTypeSet enforced_types
=
1852 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1853 return Union(preferred_types
, enforced_types
);
1856 syncer::ModelTypeSet
1857 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1858 const syncer::ModelTypeSet registered_directory_types
=
1859 GetRegisteredDirectoryDataTypes();
1860 const syncer::ModelTypeSet preferred_types
=
1861 sync_prefs_
.GetPreferredDataTypes(registered_directory_types
);
1862 const syncer::ModelTypeSet enforced_types
=
1863 Intersection(GetDataTypesFromPreferenceProviders(),
1864 registered_directory_types
);
1865 return Union(preferred_types
, enforced_types
);
1868 syncer::ModelTypeSet
1869 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1870 return sync_prefs_
.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1873 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1874 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1875 // we'll need another way to distinguish user-choosable types from
1876 // programmatically-enabled types.
1877 return GetDataTypesFromPreferenceProviders();
1880 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1881 return Union(GetRegisteredDirectoryDataTypes(),
1882 GetRegisteredNonBlockingDataTypes());
1885 syncer::ModelTypeSet
1886 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1887 syncer::ModelTypeSet registered_types
;
1888 // The directory_data_type_controllers_ are determined by command-line flags;
1889 // that's effectively what controls the values returned here.
1890 for (DataTypeController::TypeMap::const_iterator it
=
1891 directory_data_type_controllers_
.begin();
1892 it
!= directory_data_type_controllers_
.end(); ++it
) {
1893 registered_types
.Put(it
->first
);
1895 return registered_types
;
1898 syncer::ModelTypeSet
1899 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1900 return non_blocking_data_type_manager_
.GetRegisteredTypes();
1903 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1904 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1905 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1906 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1909 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1910 return backend_
->GetPassphraseType();
1913 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1914 return backend_
->GetExplicitPassphraseTime();
1917 bool ProfileSyncService::IsCryptographerReady(
1918 const syncer::BaseTransaction
* trans
) const {
1919 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1922 void ProfileSyncService::ConfigurePriorityDataTypes() {
1923 const syncer::ModelTypeSet priority_types
=
1924 Intersection(GetPreferredDirectoryDataTypes(),
1925 syncer::PriorityUserTypes());
1926 if (!priority_types
.Empty()) {
1927 const syncer::ConfigureReason reason
= HasSyncSetupCompleted() ?
1928 syncer::CONFIGURE_REASON_RECONFIGURATION
:
1929 syncer::CONFIGURE_REASON_NEW_CLIENT
;
1930 directory_data_type_manager_
->Configure(priority_types
, reason
);
1934 void ProfileSyncService::ConfigureDataTypeManager() {
1935 // Don't configure datatypes if the setup UI is still on the screen - this
1936 // is to help multi-screen setting UIs (like iOS) where they don't want to
1937 // start syncing data until the user is done configuring encryption options,
1938 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1939 // SetSetupInProgress(false).
1940 if (backend_mode_
== SYNC
&& startup_controller_
->setup_in_progress())
1943 bool restart
= false;
1944 if (!directory_data_type_manager_
) {
1946 directory_data_type_manager_
.reset(
1947 factory_
->CreateDataTypeManager(debug_info_listener_
,
1948 &directory_data_type_controllers_
,
1953 // We create the migrator at the same time.
1955 new browser_sync::BackendMigrator(
1956 profile_
->GetDebugName(), GetUserShare(),
1957 this, directory_data_type_manager_
.get(),
1958 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1959 base::Unretained(this))));
1962 syncer::ModelTypeSet types
;
1963 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1964 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1965 types
= syncer::BackupTypes();
1966 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1968 types
= GetPreferredDirectoryDataTypes();
1969 if (!HasSyncSetupCompleted()) {
1970 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1971 } else if (restart
) {
1972 // Datatype downloads on restart are generally due to newly supported
1973 // datatypes (although it's also possible we're picking up where a failed
1974 // previous configuration left off).
1975 // TODO(sync): consider detecting configuration recovery and setting
1976 // the reason here appropriately.
1977 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1979 // The user initiated a reconfiguration (either to add or remove types).
1980 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1984 directory_data_type_manager_
->Configure(types
, reason
);
1987 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1988 if (backend_
.get() && backend_initialized_
) {
1989 return backend_
->GetUserShare();
1995 syncer::sessions::SyncSessionSnapshot
1996 ProfileSyncService::GetLastSessionSnapshot() const {
1998 return backend_
->GetLastSessionSnapshot();
1999 return syncer::sessions::SyncSessionSnapshot();
2002 bool ProfileSyncService::HasUnsyncedItems() const {
2003 if (HasSyncingBackend() && backend_initialized_
) {
2004 return backend_
->HasUnsyncedItems();
2010 browser_sync::BackendMigrator
*
2011 ProfileSyncService::GetBackendMigratorForTest() {
2012 return migrator_
.get();
2015 void ProfileSyncService::GetModelSafeRoutingInfo(
2016 syncer::ModelSafeRoutingInfo
* out
) const {
2017 if (backend_
.get() && backend_initialized_
) {
2018 backend_
->GetModelSafeRoutingInfo(out
);
2024 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
2025 scoped_ptr
<base::ListValue
> result(new base::ListValue());
2027 if (!backend_
.get() || !backend_initialized_
) {
2028 return result
.release();
2031 DataTypeStatusTable::TypeErrorMap error_map
=
2032 data_type_status_table_
.GetAllErrors();
2033 ModelTypeSet active_types
;
2034 ModelTypeSet passive_types
;
2035 ModelSafeRoutingInfo routing_info
;
2036 backend_
->GetModelSafeRoutingInfo(&routing_info
);
2037 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
2038 it
!= routing_info
.end(); ++it
) {
2039 if (it
->second
== syncer::GROUP_PASSIVE
) {
2040 passive_types
.Put(it
->first
);
2042 active_types
.Put(it
->first
);
2046 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2047 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2048 ModelTypeSet registered
= GetRegisteredDataTypes();
2049 scoped_ptr
<base::DictionaryValue
> type_status_header(
2050 new base::DictionaryValue());
2052 type_status_header
->SetString("name", "Model Type");
2053 type_status_header
->SetString("status", "header");
2054 type_status_header
->SetString("value", "Group Type");
2055 type_status_header
->SetString("num_entries", "Total Entries");
2056 type_status_header
->SetString("num_live", "Live Entries");
2057 result
->Append(type_status_header
.release());
2059 scoped_ptr
<base::DictionaryValue
> type_status
;
2060 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2061 ModelType type
= it
.Get();
2063 type_status
.reset(new base::DictionaryValue());
2064 type_status
->SetString("name", ModelTypeToString(type
));
2066 if (error_map
.find(type
) != error_map
.end()) {
2067 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2068 DCHECK(error
.IsSet());
2069 switch (error
.GetSeverity()) {
2070 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2071 std::string error_text
= "Error: " + error
.location().ToString() +
2072 ", " + error
.GetMessagePrefix() + error
.message();
2073 type_status
->SetString("status", "error");
2074 type_status
->SetString("value", error_text
);
2077 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2078 type_status
->SetString("status", "disabled");
2079 type_status
->SetString("value", error
.message());
2082 NOTREACHED() << "Unexpected error severity.";
2085 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2086 // Show a proxy type in "ok" state unless it is disabled by user.
2087 DCHECK(!throttled_types
.Has(type
));
2088 type_status
->SetString("status", "ok");
2089 type_status
->SetString("value", "Passive");
2090 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2091 type_status
->SetString("status", "warning");
2092 type_status
->SetString("value", "Passive, Throttled");
2093 } else if (passive_types
.Has(type
)) {
2094 type_status
->SetString("status", "warning");
2095 type_status
->SetString("value", "Passive");
2096 } else if (throttled_types
.Has(type
)) {
2097 type_status
->SetString("status", "warning");
2098 type_status
->SetString("value", "Throttled");
2099 } else if (GetRegisteredNonBlockingDataTypes().Has(type
)) {
2100 type_status
->SetString("status", "ok");
2101 type_status
->SetString("value", "Non-Blocking");
2102 } else if (active_types
.Has(type
)) {
2103 type_status
->SetString("status", "ok");
2104 type_status
->SetString("value", "Active: " +
2105 ModelSafeGroupToString(routing_info
[type
]));
2107 type_status
->SetString("status", "warning");
2108 type_status
->SetString("value", "Disabled by User");
2111 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2112 detailed_status
.num_to_delete_entries_by_type
[type
];
2113 type_status
->SetInteger("num_entries",
2114 detailed_status
.num_entries_by_type
[type
]);
2115 type_status
->SetInteger("num_live", live_count
);
2117 result
->Append(type_status
.release());
2119 return result
.release();
2122 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2125 backend_
->DeactivateDataType(type
);
2128 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2129 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2130 // If the backend isn't running yet, OnBackendInitialized() will call this
2131 // method again after the backend starts up.
2132 if (cached_passphrase_
.empty() || !backend_initialized())
2135 // Backend is up and running, so we can consume the cached passphrase.
2136 std::string passphrase
= cached_passphrase_
;
2137 cached_passphrase_
.clear();
2139 // If we need a passphrase to decrypt data, try the cached passphrase.
2140 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2141 if (SetDecryptionPassphrase(passphrase
)) {
2142 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2147 // If we get here, we don't have pending keys (or at least, the passphrase
2148 // doesn't decrypt them) - just try to re-encrypt using the encryption
2150 if (!IsUsingSecondaryPassphrase())
2151 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2154 void ProfileSyncService::RequestAccessToken() {
2155 // Only one active request at a time.
2156 if (access_token_request_
!= NULL
)
2158 request_access_token_retry_timer_
.Stop();
2159 OAuth2TokenService::ScopeSet oauth2_scopes
;
2160 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2162 // Invalidate previous token, otherwise token service will return the same
2164 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2165 if (!access_token_
.empty()) {
2166 oauth2_token_service_
->InvalidateToken(
2167 account_id
, oauth2_scopes
, access_token_
);
2170 access_token_
.clear();
2172 token_request_time_
= base::Time::Now();
2173 token_receive_time_
= base::Time();
2174 next_token_request_time_
= base::Time();
2175 access_token_request_
=
2176 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2179 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2180 PassphraseType type
) {
2181 // This should only be called when the backend has been initialized.
2182 DCHECK(backend_initialized());
2183 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2184 "Data is already encrypted using an explicit passphrase";
2185 DCHECK(!(type
== EXPLICIT
&&
2186 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2187 "Can not set explicit passphrase when decryption is needed.";
2189 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2190 << " passphrase for encryption.";
2191 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2192 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2193 // keys. Hence, as long as we're not trying to do an invalid passphrase
2194 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2195 // will succeed. If for some reason a new encryption key arrives via
2196 // sync later, the SBH will trigger another OnPassphraseRequired().
2197 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2200 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2203 bool ProfileSyncService::SetDecryptionPassphrase(
2204 const std::string
& passphrase
) {
2205 if (IsPassphraseRequired()) {
2206 DVLOG(1) << "Setting passphrase for decryption.";
2207 return backend_
->SetDecryptionPassphrase(passphrase
);
2209 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2210 "IsPassphraseRequired() is false.";
2215 bool ProfileSyncService::EncryptEverythingAllowed() const {
2216 return encrypt_everything_allowed_
;
2219 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2220 DCHECK(allowed
|| !backend_initialized() || !EncryptEverythingEnabled());
2221 encrypt_everything_allowed_
= allowed
;
2224 void ProfileSyncService::EnableEncryptEverything() {
2225 DCHECK(EncryptEverythingAllowed());
2227 // Tests override backend_initialized() to always return true, so we
2228 // must check that instead of |backend_initialized_|.
2229 // TODO(akalin): Fix the above. :/
2230 DCHECK(backend_initialized());
2231 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2232 // problems around cancelling encryption in the background (crbug.com/119649).
2233 if (!encrypt_everything_
)
2234 encryption_pending_
= true;
2237 bool ProfileSyncService::encryption_pending() const {
2238 // We may be called during the setup process before we're
2239 // initialized (via IsEncryptedDatatypeEnabled and
2240 // IsPassphraseRequiredForDecryption).
2241 return encryption_pending_
;
2244 bool ProfileSyncService::EncryptEverythingEnabled() const {
2245 DCHECK(backend_initialized_
);
2246 return encrypt_everything_
|| encryption_pending_
;
2249 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2250 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2251 // We may be called during the setup process before we're
2252 // initialized. In this case, we default to the sensitive types.
2253 return encrypted_types_
;
2256 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2257 if (is_sync_managed
) {
2260 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2261 startup_controller_
->TryStart();
2265 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2266 const std::string
& username
,
2267 const std::string
& password
) {
2268 if (!sync_prefs_
.IsStartSuppressed() && !password
.empty()) {
2269 cached_passphrase_
= password
;
2270 // Try to consume the passphrase we just cached. If the sync backend
2271 // is not running yet, the passphrase will remain cached until the
2272 // backend starts up.
2273 ConsumeCachedPassphraseIfPossible();
2275 #if defined(OS_CHROMEOS)
2276 RefreshSpareBootstrapToken(password
);
2278 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE
) {
2279 // Track the fact that we're still waiting for auth to complete.
2280 is_auth_in_progress_
= true;
2284 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2285 const std::string
& username
) {
2286 sync_disabled_by_admin_
= false;
2289 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2290 need_backup_
= true;
2291 backup_finished_
= false;
2295 void ProfileSyncService::AddObserver(
2296 ProfileSyncServiceBase::Observer
* observer
) {
2297 observers_
.AddObserver(observer
);
2300 void ProfileSyncService::RemoveObserver(
2301 ProfileSyncServiceBase::Observer
* observer
) {
2302 observers_
.RemoveObserver(observer
);
2305 void ProfileSyncService::AddProtocolEventObserver(
2306 browser_sync::ProtocolEventObserver
* observer
) {
2307 protocol_event_observers_
.AddObserver(observer
);
2308 if (HasSyncingBackend()) {
2309 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2313 void ProfileSyncService::RemoveProtocolEventObserver(
2314 browser_sync::ProtocolEventObserver
* observer
) {
2315 protocol_event_observers_
.RemoveObserver(observer
);
2316 if (HasSyncingBackend() &&
2317 !protocol_event_observers_
.might_have_observers()) {
2318 backend_
->DisableProtocolEventForwarding();
2322 void ProfileSyncService::AddTypeDebugInfoObserver(
2323 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2324 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2325 if (type_debug_info_observers_
.might_have_observers() &&
2326 backend_initialized_
) {
2327 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2331 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2332 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2333 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2334 if (!type_debug_info_observers_
.might_have_observers() &&
2335 backend_initialized_
) {
2336 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2340 void ProfileSyncService::AddPreferenceProvider(
2341 SyncTypePreferenceProvider
* provider
) {
2342 DCHECK(!HasPreferenceProvider(provider
))
2343 << "Providers may only be added once!";
2344 preference_providers_
.insert(provider
);
2347 void ProfileSyncService::RemovePreferenceProvider(
2348 SyncTypePreferenceProvider
* provider
) {
2349 DCHECK(HasPreferenceProvider(provider
))
2350 << "Only providers that have been added before can be removed!";
2351 preference_providers_
.erase(provider
);
2354 bool ProfileSyncService::HasPreferenceProvider(
2355 SyncTypePreferenceProvider
* provider
) const {
2356 return preference_providers_
.count(provider
) > 0;
2361 class GetAllNodesRequestHelper
2362 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2364 GetAllNodesRequestHelper(
2365 syncer::ModelTypeSet requested_types
,
2366 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2368 void OnReceivedNodesForTypes(
2369 const std::vector
<syncer::ModelType
>& types
,
2370 ScopedVector
<base::ListValue
> scoped_node_lists
);
2373 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2374 virtual ~GetAllNodesRequestHelper();
2376 scoped_ptr
<base::ListValue
> result_accumulator_
;
2378 syncer::ModelTypeSet awaiting_types_
;
2379 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2382 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2383 syncer::ModelTypeSet requested_types
,
2384 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2385 : result_accumulator_(new base::ListValue()),
2386 awaiting_types_(requested_types
),
2387 callback_(callback
) {}
2389 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2390 if (!awaiting_types_
.Empty()) {
2392 << "GetAllNodesRequest deleted before request was fulfilled. "
2393 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2397 // Called when the set of nodes for a type or set of types has been returned.
2399 // The nodes for several types can be returned at the same time by specifying
2400 // their types in the |types| array, and putting their results at the
2401 // correspnding indices in the |scoped_node_lists|.
2402 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2403 const std::vector
<syncer::ModelType
>& types
,
2404 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2405 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2407 // Take unsafe ownership of the node list.
2408 std::vector
<base::ListValue
*> node_lists
;
2409 scoped_node_lists
.release(&node_lists
);
2411 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2412 const ModelType type
= types
[i
];
2413 base::ListValue
* node_list
= node_lists
[i
];
2415 // Add these results to our list.
2416 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2417 type_dict
->SetString("type", ModelTypeToString(type
));
2418 type_dict
->Set("nodes", node_list
);
2419 result_accumulator_
->Append(type_dict
.release());
2421 // Remember that this part of the request is satisfied.
2422 awaiting_types_
.Remove(type
);
2425 if (awaiting_types_
.Empty()) {
2426 callback_
.Run(result_accumulator_
.Pass());
2433 void ProfileSyncService::GetAllNodes(
2434 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2435 ModelTypeSet directory_types
= GetRegisteredDirectoryDataTypes();
2436 directory_types
.PutAll(syncer::ControlTypes());
2437 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2438 new GetAllNodesRequestHelper(directory_types
, callback
);
2440 if (!backend_initialized_
) {
2441 // If there's no backend available to fulfill the request, handle it here.
2442 ScopedVector
<base::ListValue
> empty_results
;
2443 std::vector
<ModelType
> type_vector
;
2444 for (ModelTypeSet::Iterator it
= directory_types
.First();
2445 it
.Good(); it
.Inc()) {
2446 type_vector
.push_back(it
.Get());
2447 empty_results
.push_back(new base::ListValue());
2449 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2451 backend_
->GetAllNodesForTypes(
2453 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2457 bool ProfileSyncService::HasObserver(
2458 const ProfileSyncServiceBase::Observer
* observer
) const {
2459 return observers_
.HasObserver(observer
);
2462 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2463 return sync_js_controller_
.AsWeakPtr();
2466 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2467 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2471 bool ProfileSyncService::IsSyncEnabled() {
2472 // We have switches::kEnableSync just in case we need to change back to
2473 // sync-disabled-by-default on a platform.
2474 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2475 switches::kDisableSync
);
2478 bool ProfileSyncService::IsManaged() const {
2479 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2482 void ProfileSyncService::StopAndSuppress() {
2483 sync_prefs_
.SetStartSuppressed(true);
2484 if (HasSyncingBackend()) {
2485 backend_
->UnregisterInvalidationIds();
2487 ShutdownImpl(syncer::STOP_SYNC
);
2490 bool ProfileSyncService::IsStartSuppressed() const {
2491 return sync_prefs_
.IsStartSuppressed();
2494 SigninManagerBase
* ProfileSyncService::signin() const {
2497 return signin_
->GetOriginal();
2500 void ProfileSyncService::UnsuppressAndStart() {
2502 sync_prefs_
.SetStartSuppressed(false);
2503 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2504 startup_controller_
->TryStart();
2507 void ProfileSyncService::AcknowledgeSyncedTypes() {
2508 sync_prefs_
.AcknowledgeSyncedTypes(GetRegisteredDataTypes());
2511 void ProfileSyncService::ReconfigureDatatypeManager() {
2512 // If we haven't initialized yet, don't configure the DTM as it could cause
2513 // association to start before a Directory has even been created.
2514 if (backend_initialized_
) {
2515 DCHECK(backend_
.get());
2516 ConfigureDataTypeManager();
2517 } else if (HasUnrecoverableError()) {
2518 // There is nothing more to configure. So inform the listeners,
2521 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2522 << "Unrecoverable error.";
2524 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2529 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2531 syncer::ModelTypeSet types
;
2532 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2533 preference_providers_
.begin();
2534 it
!= preference_providers_
.end();
2536 types
.PutAll((*it
)->GetPreferredDataTypes());
2541 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2543 return data_type_status_table_
;
2546 void ProfileSyncService::OnInternalUnrecoverableError(
2547 const tracked_objects::Location
& from_here
,
2548 const std::string
& message
,
2549 bool delete_sync_database
,
2550 UnrecoverableErrorReason reason
) {
2551 DCHECK(!HasUnrecoverableError());
2552 unrecoverable_error_reason_
= reason
;
2553 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2556 syncer::SyncManagerFactory::MANAGER_TYPE
2557 ProfileSyncService::GetManagerType() const {
2558 switch (backend_mode_
) {
2560 return syncer::SyncManagerFactory::NORMAL
;
2562 return syncer::SyncManagerFactory::BACKUP
;
2564 return syncer::SyncManagerFactory::ROLLBACK
;
2568 return syncer::SyncManagerFactory::NORMAL
;
2571 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2572 return request_access_token_retry_timer_
.IsRunning();
2575 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2576 return access_token_
;
2579 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2580 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2583 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2584 return sessions_sync_manager_
.get();
2587 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2588 return device_info_sync_service_
.get();
2591 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2592 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED
),
2593 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2594 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2596 ProfileSyncService::SyncTokenStatus
2597 ProfileSyncService::GetSyncTokenStatus() const {
2598 SyncTokenStatus status
;
2599 status
.connection_status_update_time
= connection_status_update_time_
;
2600 status
.connection_status
= connection_status_
;
2601 status
.token_request_time
= token_request_time_
;
2602 status
.token_receive_time
= token_receive_time_
;
2603 status
.last_get_token_error
= last_get_token_error_
;
2604 if (request_access_token_retry_timer_
.IsRunning())
2605 status
.next_token_request_time
= next_token_request_time_
;
2609 void ProfileSyncService::OverrideNetworkResourcesForTest(
2610 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2611 network_resources_
= network_resources
.Pass();
2614 bool ProfileSyncService::HasSyncingBackend() const {
2615 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2618 void ProfileSyncService::UpdateFirstSyncTimePref() {
2619 if (signin_
->GetEffectiveUsername().empty()) {
2620 // Clear if user's not signed in and rollback is done.
2621 if (backend_mode_
!= ROLLBACK
)
2622 sync_prefs_
.ClearFirstSyncTime();
2623 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2624 backend_mode_
== SYNC
) {
2625 // Set if not set before and it's syncing now.
2626 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2630 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2631 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2632 if (first_sync_time
.is_null())
2635 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2641 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2642 BrowsingDataRemover::Observer
* observer
) {
2643 browsing_data_remover_observer_
= observer
;
2646 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2647 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2651 clear_browsing_data_
= c
;
2654 GURL
ProfileSyncService::GetSyncServiceURL(
2655 const base::CommandLine
& command_line
) {
2656 // By default, dev, canary, and unbranded Chromium users will go to the
2657 // development servers. Development servers have more features than standard
2658 // sync servers. Users with officially-branded Chrome stable and beta builds
2659 // will go to the standard sync servers.
2660 GURL
result(kDevServerUrl
);
2662 chrome::VersionInfo::Channel channel
= chrome::VersionInfo::GetChannel();
2663 if (channel
== chrome::VersionInfo::CHANNEL_STABLE
||
2664 channel
== chrome::VersionInfo::CHANNEL_BETA
) {
2665 result
= GURL(kSyncServerUrl
);
2668 // Override the sync server URL from the command-line, if sync server
2669 // command-line argument exists.
2670 if (command_line
.HasSwitch(switches::kSyncServiceURL
)) {
2671 std::string
value(command_line
.GetSwitchValueASCII(
2672 switches::kSyncServiceURL
));
2673 if (!value
.empty()) {
2674 GURL
custom_sync_url(value
);
2675 if (custom_sync_url
.is_valid()) {
2676 result
= custom_sync_url
;
2678 LOG(WARNING
) << "The following sync URL specified at the command-line "
2679 << "is invalid: " << value
;
2686 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2687 DCHECK_EQ(backend_mode_
, SYNC
);
2689 #if defined(ENABLE_PRE_SYNC_BACKUP)
2690 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2691 // Check backup once a day.
2692 if (!last_backup_time_
&&
2693 (last_synced_time
.is_null() ||
2694 base::Time::Now() - last_synced_time
>=
2695 base::TimeDelta::FromDays(1))) {
2696 // If sync thread is set, need to serialize check on sync thread after
2697 // closing backup DB.
2699 sync_thread_
->message_loop_proxy()->PostTask(
2701 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2702 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2703 base::MessageLoopProxy::current(),
2704 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2705 weak_factory_
.GetWeakPtr())));
2707 content::BrowserThread::PostTask(
2708 content::BrowserThread::FILE, FROM_HERE
,
2709 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2710 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2711 base::MessageLoopProxy::current(),
2712 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2713 weak_factory_
.GetWeakPtr())));
2719 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2720 last_backup_time_
.reset(new base::Time(backup_time
));
2722 DCHECK(device_info_sync_service_
);
2723 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2726 void ProfileSyncService::TryStartSyncAfterBackup() {
2727 startup_controller_
->Reset(GetRegisteredDataTypes());
2728 startup_controller_
->TryStart();
2731 void ProfileSyncService::CleanUpBackup() {
2732 sync_prefs_
.ClearFirstSyncTime();
2733 profile_
->GetIOTaskRunner()->PostTask(
2735 base::Bind(base::IgnoreResult(base::DeleteFile
),
2736 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2740 bool ProfileSyncService::NeedBackup() const {
2741 return need_backup_
;
2744 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2745 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2748 void ProfileSyncService::FlushDirectory() const {
2749 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2750 // If sync is not initialized yet, we fail silently.
2751 if (backend_initialized_
)
2752 backend_
->FlushDirectory();
2755 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2756 return directory_path_
;
2759 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2761 return sync_thread_
->message_loop();
2762 } else if (backend_
) {
2763 return backend_
->GetSyncLoopForTesting();
2769 void ProfileSyncService::RemoveClientFromServer() const {
2770 if (!backend_initialized_
) return;
2771 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2772 std::string birthday
;
2773 syncer::UserShare
* user_share
= GetUserShare();
2774 if (user_share
&& user_share
->directory
.get()) {
2775 birthday
= user_share
->directory
->store_birthday();
2777 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2778 sync_stopped_reporter_
->ReportSyncStopped(
2779 access_token_
, cache_guid
, birthday
);