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/profiler/scoped_tracker.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browsing_data/browsing_data_helper.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
33 #include "chrome/browser/net/chrome_cookie_notification_details.h"
34 #include "chrome/browser/password_manager/password_store_factory.h"
35 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
36 #include "chrome/browser/prefs/pref_service_syncable.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/signin/about_signin_internals_factory.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/backend_migrator.h"
43 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
44 #include "chrome/browser/sync/glue/favicon_cache.h"
45 #include "chrome/browser/sync/glue/sync_backend_host.h"
46 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
47 #include "chrome/browser/sync/glue/sync_start_util.h"
48 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
49 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
50 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
51 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
52 #include "chrome/browser/sync/sync_error_controller.h"
53 #include "chrome/browser/sync/sync_stopped_reporter.h"
54 #include "chrome/browser/sync/sync_type_preference_provider.h"
55 #include "chrome/browser/ui/browser.h"
56 #include "chrome/browser/ui/browser_list.h"
57 #include "chrome/browser/ui/browser_window.h"
58 #include "chrome/browser/ui/global_error/global_error_service.h"
59 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
60 #include "chrome/common/chrome_switches.h"
61 #include "chrome/common/chrome_version_info.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/url_constants.h"
64 #include "chrome/grit/generated_resources.h"
65 #include "components/autofill/core/common/autofill_pref_names.h"
66 #include "components/invalidation/invalidation_service.h"
67 #include "components/invalidation/profile_invalidation_provider.h"
68 #include "components/password_manager/core/browser/password_store.h"
69 #include "components/pref_registry/pref_registry_syncable.h"
70 #include "components/signin/core/browser/about_signin_internals.h"
71 #include "components/signin/core/browser/profile_oauth2_token_service.h"
72 #include "components/signin/core/browser/signin_manager.h"
73 #include "components/signin/core/browser/signin_metrics.h"
74 #include "components/sync_driver/change_processor.h"
75 #include "components/sync_driver/data_type_controller.h"
76 #include "components/sync_driver/device_info.h"
77 #include "components/sync_driver/pref_names.h"
78 #include "components/sync_driver/system_encryptor.h"
79 #include "components/sync_driver/user_selectable_sync_type.h"
80 #include "content/public/browser/browser_thread.h"
81 #include "content/public/browser/notification_details.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/notification_source.h"
84 #include "net/cookies/cookie_monster.h"
85 #include "net/url_request/url_request_context_getter.h"
86 #include "sync/api/sync_error.h"
87 #include "sync/internal_api/public/configure_reason.h"
88 #include "sync/internal_api/public/http_bridge_network_resources.h"
89 #include "sync/internal_api/public/network_resources.h"
90 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
91 #include "sync/internal_api/public/shutdown_reason.h"
92 #include "sync/internal_api/public/sync_context_proxy.h"
93 #include "sync/internal_api/public/sync_encryption_handler.h"
94 #include "sync/internal_api/public/util/experiments.h"
95 #include "sync/internal_api/public/util/sync_db_util.h"
96 #include "sync/internal_api/public/util/sync_string_conversions.h"
97 #include "sync/js/js_event_details.h"
98 #include "sync/protocol/sync.pb.h"
99 #include "sync/syncable/directory.h"
100 #include "sync/util/cryptographer.h"
101 #include "ui/base/l10n/l10n_util.h"
102 #include "ui/base/l10n/time_format.h"
104 #if defined(OS_ANDROID)
105 #include "sync/internal_api/public/read_transaction.h"
108 using browser_sync::NotificationServiceSessionsRouter
;
109 using browser_sync::ProfileSyncServiceStartBehavior
;
110 using browser_sync::SessionsSyncManager
;
111 using browser_sync::SyncBackendHost
;
112 using sync_driver::ChangeProcessor
;
113 using sync_driver::DataTypeController
;
114 using sync_driver::DataTypeManager
;
115 using sync_driver::DataTypeStatusTable
;
116 using sync_driver::DeviceInfoSyncService
;
117 using syncer::ModelType
;
118 using syncer::ModelTypeSet
;
119 using syncer::JsBackend
;
120 using syncer::JsController
;
121 using syncer::JsEventDetails
;
122 using syncer::JsEventHandler
;
123 using syncer::ModelSafeRoutingInfo
;
124 using syncer::SyncCredentials
;
125 using syncer::SyncProtocolError
;
126 using syncer::WeakHandle
;
128 typedef GoogleServiceAuthError AuthError
;
130 const char* ProfileSyncService::kSyncServerUrl
=
131 "https://clients4.google.com/chrome-sync";
133 const char* ProfileSyncService::kDevServerUrl
=
134 "https://clients4.google.com/chrome-sync/dev";
136 const char kSyncUnrecoverableErrorHistogram
[] =
137 "Sync.UnrecoverableErrors";
139 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
140 // Number of initial errors (in sequence) to ignore before applying
141 // exponential back-off rules.
144 // Initial delay for exponential back-off in ms.
147 // Factor by which the waiting time will be multiplied.
150 // Fuzzing percentage. ex: 10% will spread requests randomly
151 // between 90%-100% of the calculated time.
154 // Maximum amount of time we are willing to delay our request in ms.
155 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
156 // RequestAccessToken on connection state change after backoff
157 1000 * 3600 * 4, // 4 hours.
159 // Time to keep an entry from being discarded even when it
160 // has no significant state, -1 to never discard.
163 // Don't use initial delay unless the last request was an error.
167 static const base::FilePath::CharType kSyncDataFolderName
[] =
168 FILE_PATH_LITERAL("Sync Data");
170 static const base::FilePath::CharType kSyncBackupDataFolderName
[] =
171 FILE_PATH_LITERAL("Sync Data Backup");
175 void ClearBrowsingData(BrowsingDataRemover::Observer
* observer
,
179 // BrowsingDataRemover deletes itself when it's done.
180 BrowsingDataRemover
* remover
= BrowsingDataRemover::CreateForRange(
181 profile
, start
, end
);
183 remover
->AddObserver(observer
);
184 remover
->Remove(BrowsingDataRemover::REMOVE_ALL
,
185 BrowsingDataHelper::ALL
);
187 scoped_refptr
<password_manager::PasswordStore
> password
=
188 PasswordStoreFactory::GetForProfile(profile
,
189 ServiceAccessType::EXPLICIT_ACCESS
);
190 password
->RemoveLoginsSyncedBetween(start
, end
);
193 // Perform the actual sync data folder deletion.
194 // This should only be called on the sync thread.
195 void DeleteSyncDataFolder(const base::FilePath
& directory_path
) {
196 if (base::DirectoryExists(directory_path
)) {
197 if (!base::DeleteFile(directory_path
, true))
198 LOG(DFATAL
) << "Could not delete the Sync Data folder.";
202 } // anonymous namespace
204 bool ShouldShowActionOnUI(
205 const syncer::SyncProtocolError
& error
) {
206 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
207 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
208 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
211 ProfileSyncService::ProfileSyncService(
212 scoped_ptr
<ProfileSyncComponentsFactory
> factory
,
214 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
215 ProfileOAuth2TokenService
* oauth2_token_service
,
216 ProfileSyncServiceStartBehavior start_behavior
)
217 : OAuth2TokenService::Consumer("sync"),
218 last_auth_error_(AuthError::AuthErrorNone()),
219 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
220 factory_(factory
.Pass()),
222 sync_prefs_(profile_
->GetPrefs()),
224 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
225 is_first_time_sync_configure_(false),
226 backend_initialized_(false),
227 sync_disabled_by_admin_(false),
228 is_auth_in_progress_(false),
229 signin_(signin_wrapper
.Pass()),
230 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
231 expect_sync_configuration_aborted_(false),
232 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
233 encrypt_everything_allowed_(true),
234 encrypt_everything_(false),
235 encryption_pending_(false),
236 configure_status_(DataTypeManager::UNKNOWN
),
237 oauth2_token_service_(oauth2_token_service
),
238 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
239 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
240 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
241 network_resources_(new syncer::HttpBridgeNetworkResources
),
244 backup_finished_(false),
245 clear_browsing_data_(base::Bind(&ClearBrowsingData
)),
246 browsing_data_remover_observer_(NULL
),
247 sync_stopped_reporter_(
248 new browser_sync::SyncStoppedReporter(
250 profile_
->GetRequestContext(),
251 browser_sync::SyncStoppedReporter::ResultCallback())),
253 startup_controller_weak_factory_(this) {
254 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
256 startup_controller_
.reset(new browser_sync::StartupController(
258 oauth2_token_service
,
261 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
262 startup_controller_weak_factory_
.GetWeakPtr(),
264 backup_rollback_controller_
.reset(new browser_sync::BackupRollbackController(
267 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
268 startup_controller_weak_factory_
.GetWeakPtr(),
270 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
271 startup_controller_weak_factory_
.GetWeakPtr(),
273 syncer::SyncableService::StartSyncFlare
flare(
274 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
275 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
276 new NotificationServiceSessionsRouter(profile
, flare
));
278 DCHECK(factory_
.get());
279 local_device_
= factory_
->CreateLocalDeviceInfoProvider();
280 sessions_sync_manager_
.reset(
281 new SessionsSyncManager(profile
, local_device_
.get(), router
.Pass()));
282 device_info_sync_service_
.reset(
283 new DeviceInfoSyncService(local_device_
.get()));
286 ProfileSyncService::~ProfileSyncService() {
287 sync_prefs_
.RemoveSyncPrefObserver(this);
288 // Shutdown() should have been called before destruction.
289 CHECK(!backend_initialized_
);
292 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
293 // Exit if sync is not allowed or not requested.
294 if (!IsSyncAllowed() || !IsSyncRequested())
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 // If sync isn't allowed, the only thing to do is to turn it off.
317 if (!IsSyncAllowed()) {
322 RegisterAuthNotifications();
324 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
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_
= !IsSignedIn() || sync_prefs_
.GetFirstSyncTime().is_null();
352 // Try to resume rollback if it didn't finish in last session.
353 running_rollback
= backup_rollback_controller_
->StartRollback();
355 need_backup_
= false;
358 #if defined(ENABLE_PRE_SYNC_BACKUP)
359 if (!running_rollback
&& !IsSignedIn()) {
363 DCHECK(!running_rollback
);
366 memory_pressure_listener_
.reset(new base::MemoryPressureListener(base::Bind(
367 &ProfileSyncService::OnMemoryPressure
, weak_factory_
.GetWeakPtr())));
368 startup_controller_
->Reset(GetRegisteredDataTypes());
369 startup_controller_
->TryStart();
372 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
373 DCHECK(!backend_initialized());
374 if (!HasSyncSetupCompleted())
377 // There was a bug where OnUserChoseDatatypes was not properly called on
378 // configuration (see crbug.com/154940). We detect this by checking whether
379 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
380 // completed, it means sync was not properly configured, so we manually
381 // set kSyncKeepEverythingSynced.
382 PrefService
* const pref_service
= profile_
->GetPrefs();
385 if (GetPreferredDataTypes().Size() > 1)
388 const PrefService::Preference
* keep_everything_synced
=
389 pref_service
->FindPreference(
390 sync_driver::prefs::kSyncKeepEverythingSynced
);
391 // This will be false if the preference was properly set or if it's controlled
393 if (!keep_everything_synced
->IsDefaultValue())
396 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
397 // types now, before we configure.
398 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
399 sync_prefs_
.SetKeepEverythingSynced(true);
400 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
403 void ProfileSyncService::StartSyncingWithServer() {
405 backend_
->StartSyncingWithServer();
408 void ProfileSyncService::RegisterAuthNotifications() {
409 oauth2_token_service_
->AddObserver(this);
411 signin()->AddObserver(this);
414 void ProfileSyncService::UnregisterAuthNotifications() {
416 signin()->RemoveObserver(this);
417 oauth2_token_service_
->RemoveObserver(this);
420 void ProfileSyncService::RegisterDataTypeController(
421 DataTypeController
* data_type_controller
) {
423 directory_data_type_controllers_
.count(data_type_controller
->type()),
425 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
426 data_type_controller
->type()));
427 directory_data_type_controllers_
[data_type_controller
->type()] =
428 data_type_controller
;
431 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type
) {
432 DCHECK_EQ(directory_data_type_controllers_
.count(type
), 0U)
433 << "Duplicate registration of type " << ModelTypeToString(type
);
435 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
436 // fixed and we have some way of telling whether or not this type should be
438 non_blocking_data_type_manager_
.RegisterType(type
, false);
441 void ProfileSyncService::InitializeNonBlockingType(
442 syncer::ModelType type
,
443 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
444 const base::WeakPtr
<syncer::ModelTypeSyncProxyImpl
>& type_sync_proxy
) {
445 non_blocking_data_type_manager_
.InitializeType(
446 type
, task_runner
, type_sync_proxy
);
449 bool ProfileSyncService::IsDataTypeControllerRunning(
450 syncer::ModelType type
) const {
451 DataTypeController::TypeMap::const_iterator iter
=
452 directory_data_type_controllers_
.find(type
);
453 if (iter
== directory_data_type_controllers_
.end()) {
456 return iter
->second
->state() == DataTypeController::RUNNING
;
459 browser_sync::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
460 if (!IsDataTypeControllerRunning(syncer::SESSIONS
))
462 return sessions_sync_manager_
.get();
465 browser_sync::FaviconCache
* ProfileSyncService::GetFaviconCache() {
466 return sessions_sync_manager_
->GetFaviconCache();
469 browser_sync::SyncedWindowDelegatesGetter
*
470 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
471 return sessions_sync_manager_
->GetSyncedWindowDelegatesGetter();
474 sync_driver::DeviceInfoTracker
* ProfileSyncService::GetDeviceInfoTracker()
476 return device_info_sync_service_
.get();
479 sync_driver::LocalDeviceInfoProvider
*
480 ProfileSyncService::GetLocalDeviceInfoProvider() {
481 return local_device_
.get();
484 void ProfileSyncService::GetDataTypeControllerStates(
485 DataTypeController::StateMap
* state_map
) const {
486 for (DataTypeController::TypeMap::const_iterator iter
=
487 directory_data_type_controllers_
.begin();
488 iter
!= directory_data_type_controllers_
.end();
490 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
493 SyncCredentials
ProfileSyncService::GetCredentials() {
494 SyncCredentials credentials
;
495 if (backend_mode_
== SYNC
) {
496 credentials
.email
= signin_
->GetEffectiveUsername();
497 DCHECK(!credentials
.email
.empty());
498 credentials
.sync_token
= access_token_
;
500 if (credentials
.sync_token
.empty())
501 credentials
.sync_token
= "credentials_lost";
503 credentials
.scope_set
.insert(signin_
->GetSyncScopeToUse());
509 bool ProfileSyncService::ShouldDeleteSyncFolder() {
510 switch (backend_mode_
) {
512 return !HasSyncSetupCompleted();
524 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
530 SyncCredentials credentials
= GetCredentials();
532 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
533 profile_
->GetRequestContext());
535 if (backend_mode_
== SYNC
&& delete_stale_data
)
538 scoped_ptr
<syncer::UnrecoverableErrorHandler
>
539 backend_unrecoverable_error_handler(
540 new browser_sync::BackendUnrecoverableErrorHandler(
541 MakeWeakHandle(weak_factory_
.GetWeakPtr())));
543 backend_
->Initialize(
544 this, sync_thread_
.Pass(), GetJsEventHandler(), sync_service_url_
,
545 credentials
, delete_stale_data
,
546 scoped_ptr
<syncer::SyncManagerFactory
>(
547 new syncer::SyncManagerFactory(GetManagerType())).Pass(),
548 backend_unrecoverable_error_handler
.Pass(),
549 base::Bind(browser_sync::ChromeReportUnrecoverableError
),
550 network_resources_
.get());
553 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
554 if (encryption_pending())
556 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
557 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
558 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
559 return !Intersection(preferred_types
, encrypted_types
).Empty();
562 void ProfileSyncService::OnProtocolEvent(
563 const syncer::ProtocolEvent
& event
) {
564 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver
,
565 protocol_event_observers_
,
566 OnProtocolEvent(event
));
569 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
570 syncer::ModelType type
,
571 const syncer::CommitCounters
& counters
) {
572 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
573 type_debug_info_observers_
,
574 OnCommitCountersUpdated(type
, counters
));
577 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
578 syncer::ModelType type
,
579 const syncer::UpdateCounters
& counters
) {
580 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
581 type_debug_info_observers_
,
582 OnUpdateCountersUpdated(type
, counters
));
585 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
586 syncer::ModelType type
,
587 const syncer::StatusCounters
& counters
) {
588 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
589 type_debug_info_observers_
,
590 OnStatusCountersUpdated(type
, counters
));
593 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
594 syncer::ModelType type
) {
595 DCHECK(syncer::UserTypes().Has(type
));
596 if (backend_
.get()) {
597 DVLOG(1) << "A data type requested sync startup, but it looks like "
598 "something else beat it to the punch.";
602 if (!GetPreferredDataTypes().Has(type
)) {
603 // We can get here as datatype SyncableServices are typically wired up
604 // to the native datatype even if sync isn't enabled.
605 DVLOG(1) << "Dropping sync startup request because type "
606 << syncer::ModelTypeToString(type
) << "not enabled.";
610 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
613 void ProfileSyncService::StartUpSlowBackendComponents(
614 ProfileSyncService::BackendMode mode
) {
615 DCHECK_NE(IDLE
, mode
);
616 if (backend_mode_
== mode
) {
620 // Backend mode transition rules:
621 // * can transit from IDLE to any other non-IDLE mode.
622 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
623 // be explicitly shut down before backup/rollback starts.
624 // * can not transit out of ROLLBACK mode until rollback is finished
625 // (successfully or unsuccessfully).
626 // * can not transit out of BACKUP mode until backup is finished
627 // (successfully or unsuccessfully).
628 // * if backup is needed, can only transit to SYNC if backup is finished,
630 if (backend_mode_
== SYNC
) {
631 LOG(DFATAL
) << "Shouldn't switch from mode SYNC to mode " << mode
;
635 if (backend_mode_
== ROLLBACK
||
636 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
637 // Wait for rollback/backup to finish before start new backend.
641 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
642 if (backend_mode_
!= BACKUP
)
643 backup_rollback_controller_
->StartBackup();
647 DVLOG(1) << "Start backend mode: " << mode
;
651 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
653 ShutdownImpl(syncer::STOP_SYNC
);
656 backend_mode_
= mode
;
658 if (backend_mode_
== BACKUP
)
659 backup_start_time_
= base::Time::Now();
661 if (backend_mode_
== SYNC
&& !backup_start_time_
.is_null()) {
662 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
663 base::Time::Now() - backup_start_time_
);
664 backup_start_time_
= base::Time();
667 if (backend_mode_
== ROLLBACK
)
668 ClearBrowsingDataSinceFirstSync();
669 else if (backend_mode_
== SYNC
)
670 CheckSyncBackupIfNeeded();
672 base::FilePath sync_folder
= backend_mode_
== SYNC
?
673 base::FilePath(kSyncDataFolderName
) :
674 base::FilePath(kSyncBackupDataFolderName
);
676 invalidation::InvalidationService
* invalidator
= NULL
;
677 if (backend_mode_
== SYNC
) {
678 invalidation::ProfileInvalidationProvider
* provider
=
679 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
682 invalidator
= provider
->GetInvalidationService();
685 directory_path_
= profile_
->GetPath().Append(sync_folder
);
688 factory_
->CreateSyncBackendHost(
689 profile_
->GetDebugName(),
692 sync_prefs_
.AsWeakPtr(),
695 // Initialize the backend. Every time we start up a new SyncBackendHost,
696 // we'll want to start from a fresh SyncDB, so delete any old one that might
698 InitializeBackend(ShouldDeleteSyncFolder());
700 UpdateFirstSyncTimePref();
702 ReportPreviousSessionMemoryWarningCount();
705 void ProfileSyncService::OnGetTokenSuccess(
706 const OAuth2TokenService::Request
* request
,
707 const std::string
& access_token
,
708 const base::Time
& expiration_time
) {
709 DCHECK_EQ(access_token_request_
, request
);
710 access_token_request_
.reset();
711 access_token_
= access_token
;
712 token_receive_time_
= base::Time::Now();
713 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
715 if (sync_prefs_
.SyncHasAuthError()) {
716 sync_prefs_
.SetSyncAuthError(false);
717 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
722 if (HasSyncingBackend())
723 backend_
->UpdateCredentials(GetCredentials());
725 startup_controller_
->TryStart();
728 void ProfileSyncService::OnGetTokenFailure(
729 const OAuth2TokenService::Request
* request
,
730 const GoogleServiceAuthError
& error
) {
731 DCHECK_EQ(access_token_request_
, request
);
732 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
733 access_token_request_
.reset();
734 last_get_token_error_
= error
;
735 switch (error
.state()) {
736 case GoogleServiceAuthError::CONNECTION_FAILED
:
737 case GoogleServiceAuthError::REQUEST_CANCELED
:
738 case GoogleServiceAuthError::SERVICE_ERROR
:
739 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
740 // Transient error. Retry after some time.
741 request_access_token_backoff_
.InformOfRequest(false);
742 next_token_request_time_
= base::Time::Now() +
743 request_access_token_backoff_
.GetTimeUntilRelease();
744 request_access_token_retry_timer_
.Start(
746 request_access_token_backoff_
.GetTimeUntilRelease(),
747 base::Bind(&ProfileSyncService::RequestAccessToken
,
748 weak_factory_
.GetWeakPtr()));
752 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
753 if (!sync_prefs_
.SyncHasAuthError()) {
754 sync_prefs_
.SetSyncAuthError(true);
755 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
756 AUTH_ERROR_ENCOUNTERED
,
762 if (error
.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
) {
763 LOG(ERROR
) << "Unexpected persistent error: " << error
.ToString();
765 // Show error to user.
766 UpdateAuthErrorState(error
);
771 void ProfileSyncService::OnRefreshTokenAvailable(
772 const std::string
& account_id
) {
773 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
775 tracked_objects::ScopedTracker
tracking_profile(
776 FROM_HERE_WITH_EXPLICIT_FUNCTION(
777 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
779 if (account_id
== signin_
->GetAccountIdToUse())
780 OnRefreshTokensLoaded();
783 void ProfileSyncService::OnRefreshTokenRevoked(
784 const std::string
& account_id
) {
785 if (!IsOAuthRefreshTokenAvailable()) {
786 access_token_
.clear();
787 // The additional check around IsOAuthRefreshTokenAvailable() above
788 // prevents us sounding the alarm if we actually have a valid token but
789 // a refresh attempt failed for any variety of reasons
790 // (e.g. flaky network). It's possible the token we do have is also
791 // invalid, but in that case we should already have (or can expect) an
792 // auth error sent from the sync backend.
793 UpdateAuthErrorState(
794 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
798 void ProfileSyncService::OnRefreshTokensLoaded() {
799 // This notification gets fired when OAuth2TokenService loads the tokens
801 // Initialize the backend if sync is enabled. If the sync token was
802 // not loaded, GetCredentials() will generate invalid credentials to
803 // cause the backend to generate an auth error (crbug.com/121755).
804 if (HasSyncingBackend()) {
805 RequestAccessToken();
807 startup_controller_
->TryStart();
811 void ProfileSyncService::Shutdown() {
812 UnregisterAuthNotifications();
814 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
815 if (sync_error_controller_
) {
816 // Destroy the SyncErrorController when the service shuts down for good.
817 RemoveObserver(sync_error_controller_
.get());
818 sync_error_controller_
.reset();
822 sync_thread_
->Stop();
825 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
827 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
828 // If the backend is already shut down when a DISABLE_SYNC happens,
829 // the data directory needs to be cleaned up here.
830 sync_thread_
->message_loop()->PostTask(FROM_HERE
,
831 base::Bind(&DeleteSyncDataFolder
, directory_path_
));
836 if (reason
== syncer::ShutdownReason::STOP_SYNC
837 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
838 RemoveClientFromServer();
841 non_blocking_data_type_manager_
.DisconnectSyncBackend();
843 // First, we spin down the backend to stop change processing as soon as
845 base::Time shutdown_start_time
= base::Time::Now();
846 backend_
->StopSyncingForShutdown();
848 // Stop all data type controllers, if needed. Note that until Stop
849 // completes, it is possible in theory to have a ChangeProcessor apply a
850 // change from a native model. In that case, it will get applied to the sync
851 // database (which doesn't get destroyed until we destroy the backend below)
852 // as an unsynced change. That will be persisted, and committed on restart.
853 if (directory_data_type_manager_
) {
854 if (directory_data_type_manager_
->state() != DataTypeManager::STOPPED
) {
855 // When aborting as part of shutdown, we should expect an aborted sync
856 // configure result, else we'll dcheck when we try to read the sync error.
857 expect_sync_configuration_aborted_
= true;
858 directory_data_type_manager_
->Stop();
860 directory_data_type_manager_
.reset();
863 // Shutdown the migrator before the backend to ensure it doesn't pull a null
866 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
868 // Move aside the backend so nobody else tries to use it while we are
870 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
871 if (doomed_backend
) {
872 sync_thread_
= doomed_backend
->Shutdown(reason
);
873 doomed_backend
.reset();
875 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
876 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
878 weak_factory_
.InvalidateWeakPtrs();
880 if (backend_mode_
== SYNC
)
881 startup_controller_
->Reset(GetRegisteredDataTypes());
883 // Don't let backup block sync regardless backup succeeded or not.
884 if (backend_mode_
== BACKUP
)
885 backup_finished_
= true;
887 // Sync could be blocked by rollback/backup. Post task to check whether sync
888 // should start after shutting down rollback/backup backend.
889 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
890 reason
!= syncer::SWITCH_MODE_SYNC
&&
891 reason
!= syncer::BROWSER_SHUTDOWN
) {
892 base::MessageLoop::current()->PostTask(
893 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
894 startup_controller_weak_factory_
.GetWeakPtr()));
897 // Clear various flags.
898 backend_mode_
= IDLE
;
899 expect_sync_configuration_aborted_
= false;
900 is_auth_in_progress_
= false;
901 backend_initialized_
= false;
902 cached_passphrase_
.clear();
903 encryption_pending_
= false;
904 encrypt_everything_
= false;
905 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
906 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
907 request_access_token_retry_timer_
.Stop();
908 // Revert to "no auth error".
909 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
910 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
914 // Mark this as a clean shutdown(without crash).
915 sync_prefs_
.SetCleanShutdown(true);
918 void ProfileSyncService::DisableForUser() {
919 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
920 // PSS clients don't think we're set up while we're shutting down.
921 sync_prefs_
.ClearPreferences();
922 ClearUnrecoverableError();
923 ShutdownImpl(syncer::DISABLE_SYNC
);
926 bool ProfileSyncService::HasSyncSetupCompleted() const {
927 return sync_prefs_
.HasSyncSetupCompleted();
930 void ProfileSyncService::SetSyncSetupCompleted() {
931 sync_prefs_
.SetSyncSetupCompleted();
934 void ProfileSyncService::UpdateLastSyncedTime() {
935 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
938 void ProfileSyncService::NotifyObservers() {
939 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
943 void ProfileSyncService::NotifySyncCycleCompleted() {
944 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
945 OnSyncCycleCompleted());
948 void ProfileSyncService::ClearStaleErrors() {
949 ClearUnrecoverableError();
950 last_actionable_error_
= SyncProtocolError();
951 // Clear the data type errors as well.
952 if (directory_data_type_manager_
.get())
953 directory_data_type_manager_
->ResetDataTypeErrors();
957 void ProfileSyncService::ClearUnrecoverableError() {
958 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
959 unrecoverable_error_message_
.clear();
960 unrecoverable_error_location_
= tracked_objects::Location();
963 // An invariant has been violated. Transition to an error state where we try
964 // to do as little work as possible, to avoid further corruption or crashes.
965 void ProfileSyncService::OnUnrecoverableError(
966 const tracked_objects::Location
& from_here
,
967 const std::string
& message
) {
968 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
969 // interface are assumed to originate within the syncer.
970 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
971 OnUnrecoverableErrorImpl(from_here
, message
, true);
974 void ProfileSyncService::OnUnrecoverableErrorImpl(
975 const tracked_objects::Location
& from_here
,
976 const std::string
& message
,
977 bool delete_sync_database
) {
978 DCHECK(HasUnrecoverableError());
979 unrecoverable_error_message_
= message
;
980 unrecoverable_error_location_
= from_here
;
982 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
983 unrecoverable_error_reason_
,
985 std::string location
;
986 from_here
.Write(true, true, &location
);
988 << "Unrecoverable error detected at " << location
989 << " -- ProfileSyncService unusable: " << message
;
991 // Shut all data types down.
992 base::MessageLoop::current()->PostTask(FROM_HERE
,
993 base::Bind(&ProfileSyncService::ShutdownImpl
,
994 weak_factory_
.GetWeakPtr(),
995 delete_sync_database
?
996 syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
999 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
1000 if (!backend_initialized_
)
1002 directory_data_type_manager_
->ReenableType(type
);
1005 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1006 if (backend_mode_
!= SYNC
)
1009 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1011 if (is_first_time_sync_configure_
) {
1012 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1014 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1017 base::Time on_backend_initialized_time
= base::Time::Now();
1018 base::TimeDelta delta
= on_backend_initialized_time
-
1019 startup_controller_
->start_backend_time();
1020 if (is_first_time_sync_configure_
) {
1021 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1023 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1027 void ProfileSyncService::PostBackendInitialization() {
1028 // Never get here for backup / restore.
1029 DCHECK_EQ(backend_mode_
, SYNC
);
1031 if (last_backup_time_
) {
1032 DCHECK(device_info_sync_service_
);
1033 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1036 if (protocol_event_observers_
.might_have_observers()) {
1037 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1040 non_blocking_data_type_manager_
.ConnectSyncBackend(
1041 backend_
->GetSyncContextProxy());
1043 if (type_debug_info_observers_
.might_have_observers()) {
1044 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1047 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1048 // backend is initialized. We want to call this before notifying observers in
1049 // case this operation affects the "passphrase required" status.
1050 ConsumeCachedPassphraseIfPossible();
1052 // The very first time the backend initializes is effectively the first time
1053 // we can say we successfully "synced". LastSyncedTime will only be null in
1054 // this case, because the pref wasn't restored on StartUp.
1055 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1056 UpdateLastSyncedTime();
1059 if (startup_controller_
->auto_start_enabled() && !FirstSetupInProgress()) {
1060 // Backend is initialized but we're not in sync setup, so this must be an
1061 // autostart - mark our sync setup as completed and we'll start syncing
1063 SetSyncSetupCompleted();
1066 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1067 // data type configuration because observer may flag setup as complete and
1068 // trigger data type configuration.
1069 if (HasSyncSetupCompleted()) {
1070 ConfigureDataTypeManager();
1072 DCHECK(FirstSetupInProgress());
1078 void ProfileSyncService::OnBackendInitialized(
1079 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1080 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1081 debug_info_listener
,
1082 const std::string
& cache_guid
,
1084 UpdateBackendInitUMA(success
);
1087 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1088 // and surface error UI to alert the user sync has stopped.
1089 // Keep the directory around for now so that on restart we will retry
1090 // again and potentially succeed in presence of transient file IO failures
1091 // or permissions issues, etc.
1093 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1094 // Unlike every other UnrecoverableError, it does not delete our sync data.
1095 // This exception made sense at the time it was implemented, but our new
1096 // directory corruption recovery mechanism makes it obsolete. By the time
1097 // we get here, we will have already tried and failed to delete the
1098 // directory. It would be no big deal if we tried to delete it again.
1099 OnInternalUnrecoverableError(FROM_HERE
,
1100 "BackendInitialize failure",
1102 ERROR_REASON_BACKEND_INIT_FAILURE
);
1106 backend_initialized_
= true;
1108 sync_js_controller_
.AttachJsBackend(js_backend
);
1109 debug_info_listener_
= debug_info_listener
;
1111 SigninClient
* signin_client
=
1112 ChromeSigninClientFactory::GetForProfile(profile_
);
1113 DCHECK(signin_client
);
1114 std::string signin_scoped_device_id
=
1115 signin_client
->GetSigninScopedDeviceId();
1117 // Initialize local device info.
1118 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1120 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1121 non_blocking_data_type_manager_
.SetPreferredTypes(GetPreferredDataTypes());
1123 // Give the DataTypeControllers a handle to the now initialized backend
1125 for (DataTypeController::TypeMap::iterator it
=
1126 directory_data_type_controllers_
.begin();
1127 it
!= directory_data_type_controllers_
.end(); ++it
) {
1128 it
->second
->OnUserShareReady(GetUserShare());
1131 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1132 ConfigureDataTypeManager();
1134 PostBackendInitialization();
1137 void ProfileSyncService::OnSyncCycleCompleted() {
1138 UpdateLastSyncedTime();
1139 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1140 // Trigger garbage collection of old sessions now that we've downloaded
1141 // any new session data.
1142 base::MessageLoop::current()->PostTask(FROM_HERE
, base::Bind(
1143 &SessionsSyncManager::DoGarbageCollection
,
1144 base::AsWeakPtr(sessions_sync_manager_
.get())));
1146 DVLOG(2) << "Notifying observers sync cycle completed";
1147 NotifySyncCycleCompleted();
1150 void ProfileSyncService::OnExperimentsChanged(
1151 const syncer::Experiments
& experiments
) {
1152 if (current_experiments_
.Matches(experiments
))
1155 current_experiments_
= experiments
;
1157 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1158 experiments
.gcm_invalidations_enabled
);
1159 profile()->GetPrefs()->SetBoolean(
1160 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1161 experiments
.wallet_sync_enabled
);
1164 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1165 is_auth_in_progress_
= false;
1166 last_auth_error_
= error
;
1173 AuthError
ConnectionStatusToAuthError(
1174 syncer::ConnectionStatus status
) {
1176 case syncer::CONNECTION_OK
:
1177 return AuthError::AuthErrorNone();
1179 case syncer::CONNECTION_AUTH_ERROR
:
1180 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1182 case syncer::CONNECTION_SERVER_ERROR
:
1183 return AuthError(AuthError::CONNECTION_FAILED
);
1187 return AuthError(AuthError::CONNECTION_FAILED
);
1193 void ProfileSyncService::OnConnectionStatusChange(
1194 syncer::ConnectionStatus status
) {
1195 connection_status_update_time_
= base::Time::Now();
1196 connection_status_
= status
;
1197 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1198 // Sync server returned error indicating that access token is invalid. It
1199 // could be either expired or access is revoked. Let's request another
1200 // access token and if access is revoked then request for token will fail
1201 // with corresponding error. If access token is repeatedly reported
1202 // invalid, there may be some issues with server, e.g. authentication
1203 // state is inconsistent on sync and token server. In that case, we
1204 // backoff token requests exponentially to avoid hammering token server
1205 // too much and to avoid getting same token due to token server's caching
1206 // policy. |request_access_token_retry_timer_| is used to backoff request
1207 // triggered by both auth error and failure talking to GAIA server.
1208 // Therefore, we're likely to reach the backoff ceiling more quickly than
1209 // you would expect from looking at the BackoffPolicy if both types of
1210 // errors happen. We shouldn't receive two errors back-to-back without
1211 // attempting a token/sync request in between, thus crank up request delay
1212 // unnecessary. This is because we won't make a sync request if we hit an
1213 // error until GAIA succeeds at sending a new token, and we won't request
1214 // a new token unless sync reports a token failure. But to be safe, don't
1215 // schedule request if this happens.
1216 if (request_access_token_retry_timer_
.IsRunning()) {
1217 // The timer to perform a request later is already running; nothing
1218 // further needs to be done at this point.
1219 } else if (request_access_token_backoff_
.failure_count() == 0) {
1220 // First time request without delay. Currently invalid token is used
1221 // to initialize sync backend and we'll always end up here. We don't
1222 // want to delay initialization.
1223 request_access_token_backoff_
.InformOfRequest(false);
1224 RequestAccessToken();
1226 request_access_token_backoff_
.InformOfRequest(false);
1227 request_access_token_retry_timer_
.Start(
1229 request_access_token_backoff_
.GetTimeUntilRelease(),
1230 base::Bind(&ProfileSyncService::RequestAccessToken
,
1231 weak_factory_
.GetWeakPtr()));
1234 // Reset backoff time after successful connection.
1235 if (status
== syncer::CONNECTION_OK
) {
1236 // Request shouldn't be scheduled at this time. But if it is, it's
1237 // possible that sync flips between OK and auth error states rapidly,
1238 // thus hammers token server. To be safe, only reset backoff delay when
1239 // no scheduled request.
1240 if (request_access_token_retry_timer_
.IsRunning()) {
1243 request_access_token_backoff_
.Reset();
1247 const GoogleServiceAuthError auth_error
=
1248 ConnectionStatusToAuthError(status
);
1249 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1250 UpdateAuthErrorState(auth_error
);
1254 void ProfileSyncService::StopSyncingPermanently() {
1255 sync_prefs_
.SetSyncRequested(false);
1259 void ProfileSyncService::OnPassphraseRequired(
1260 syncer::PassphraseRequiredReason reason
,
1261 const sync_pb::EncryptedData
& pending_keys
) {
1262 DCHECK(backend_
.get());
1263 DCHECK(backend_
->IsNigoriEnabled());
1265 // TODO(lipalani) : add this check to other locations as well.
1266 if (HasUnrecoverableError()) {
1267 // When unrecoverable error is detected we post a task to shutdown the
1268 // backend. The task might not have executed yet.
1272 DVLOG(1) << "Passphrase required with reason: "
1273 << syncer::PassphraseRequiredReasonToString(reason
);
1274 passphrase_required_reason_
= reason
;
1276 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1277 if (directory_data_type_manager_
) {
1278 // Reconfigure without the encrypted types (excluded implicitly via the
1279 // failed datatypes handler).
1280 directory_data_type_manager_
->Configure(types
,
1281 syncer::CONFIGURE_REASON_CRYPTO
);
1284 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1286 // Notify observers that the passphrase status may have changed.
1290 void ProfileSyncService::OnPassphraseAccepted() {
1291 DVLOG(1) << "Received OnPassphraseAccepted.";
1293 // If the pending keys were resolved via keystore, it's possible we never
1294 // consumed our cached passphrase. Clear it now.
1295 if (!cached_passphrase_
.empty())
1296 cached_passphrase_
.clear();
1298 // Reset passphrase_required_reason_ since we know we no longer require the
1299 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1300 // because that can be called by OnPassphraseRequired() if no encrypted data
1301 // types are enabled, and we don't want to clobber the true passphrase error.
1302 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1304 // Make sure the data types that depend on the passphrase are started at
1306 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1307 if (directory_data_type_manager_
) {
1308 // Re-enable any encrypted types if necessary.
1309 directory_data_type_manager_
->Configure(types
,
1310 syncer::CONFIGURE_REASON_CRYPTO
);
1313 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1318 void ProfileSyncService::OnEncryptedTypesChanged(
1319 syncer::ModelTypeSet encrypted_types
,
1320 bool encrypt_everything
) {
1321 encrypted_types_
= encrypted_types
;
1322 encrypt_everything_
= encrypt_everything
;
1323 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1324 DVLOG(1) << "Encrypted types changed to "
1325 << syncer::ModelTypeSetToString(encrypted_types_
)
1326 << " (encrypt everything is set to "
1327 << (encrypt_everything_
? "true" : "false") << ")";
1328 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1333 void ProfileSyncService::OnEncryptionComplete() {
1334 DVLOG(1) << "Encryption complete";
1335 if (encryption_pending_
&& encrypt_everything_
) {
1336 encryption_pending_
= false;
1337 // This is to nudge the integration tests when encryption is
1343 void ProfileSyncService::OnMigrationNeededForTypes(
1344 syncer::ModelTypeSet types
) {
1345 DCHECK(backend_initialized_
);
1346 DCHECK(directory_data_type_manager_
.get());
1348 // Migrator must be valid, because we don't sync until it is created and this
1349 // callback originates from a sync cycle.
1350 migrator_
->MigrateTypes(types
);
1353 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1354 last_actionable_error_
= error
;
1355 DCHECK_NE(last_actionable_error_
.action
,
1356 syncer::UNKNOWN_ACTION
);
1357 switch (error
.action
) {
1358 case syncer::UPGRADE_CLIENT
:
1359 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1360 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1361 case syncer::STOP_AND_RESTART_SYNC
:
1362 // TODO(lipalani) : if setup in progress we want to display these
1363 // actions in the popup. The current experience might not be optimal for
1364 // the user. We just dismiss the dialog.
1365 if (startup_controller_
->setup_in_progress()) {
1366 StopSyncingPermanently();
1367 expect_sync_configuration_aborted_
= true;
1369 // Trigger an unrecoverable error to stop syncing.
1370 OnInternalUnrecoverableError(FROM_HERE
,
1371 last_actionable_error_
.error_description
,
1373 ERROR_REASON_ACTIONABLE_ERROR
);
1375 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1376 backup_rollback_controller_
->OnRollbackReceived();
1377 // Fall through to shutdown backend and sign user out.
1378 case syncer::DISABLE_SYNC_ON_CLIENT
:
1379 StopSyncingPermanently();
1380 #if !defined(OS_CHROMEOS)
1381 // On desktop Chrome, sign out the user after a dashboard clear.
1382 // Skip sign out on ChromeOS/Android.
1383 if (!startup_controller_
->auto_start_enabled()) {
1384 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1385 signin_metrics::SERVER_FORCED_DISABLE
);
1389 case syncer::ROLLBACK_DONE
:
1390 backup_rollback_controller_
->OnRollbackDone();
1392 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1393 // Sync disabled by domain admin. we should stop syncing until next
1395 sync_disabled_by_admin_
= true;
1396 ShutdownImpl(syncer::DISABLE_SYNC
);
1403 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1404 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1405 !backup_rollback_controller_
->StartRollback())) {
1406 // Clean up backup data for sign-out only or when rollback is disabled.
1408 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1409 // Shut down ROLLBACK backend and delete backup DB.
1410 ShutdownImpl(syncer::DISABLE_SYNC
);
1411 sync_prefs_
.ClearFirstSyncTime();
1415 void ProfileSyncService::OnConfigureDone(
1416 const DataTypeManager::ConfigureResult
& result
) {
1417 configure_status_
= result
.status
;
1418 data_type_status_table_
= result
.data_type_status_table
;
1420 if (backend_mode_
!= SYNC
) {
1421 if (configure_status_
== DataTypeManager::OK
) {
1422 StartSyncingWithServer();
1424 // Backup is done after models are associated.
1425 if (backend_mode_
== BACKUP
)
1426 backup_finished_
= true;
1428 // Asynchronously check whether sync needs to start.
1429 base::MessageLoop::current()->PostTask(
1430 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1431 startup_controller_weak_factory_
.GetWeakPtr()));
1432 } else if (!expect_sync_configuration_aborted_
) {
1433 DVLOG(1) << "Backup/rollback backend failed to configure.";
1434 ShutdownImpl(syncer::STOP_SYNC
);
1440 // We should have cleared our cached passphrase before we get here (in
1441 // OnBackendInitialized()).
1442 DCHECK(cached_passphrase_
.empty());
1444 if (!sync_configure_start_time_
.is_null()) {
1445 if (result
.status
== DataTypeManager::OK
) {
1446 base::Time sync_configure_stop_time
= base::Time::Now();
1447 base::TimeDelta delta
= sync_configure_stop_time
-
1448 sync_configure_start_time_
;
1449 if (is_first_time_sync_configure_
) {
1450 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1452 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1456 sync_configure_start_time_
= base::Time();
1459 // Notify listeners that configuration is done.
1460 content::NotificationService::current()->Notify(
1461 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1462 content::Source
<ProfileSyncService
>(this),
1463 content::NotificationService::NoDetails());
1465 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1466 // The possible status values:
1467 // ABORT - Configuration was aborted. This is not an error, if
1468 // initiated by user.
1469 // OK - Some or all types succeeded.
1470 // Everything else is an UnrecoverableError. So treat it as such.
1472 // First handle the abort case.
1473 if (configure_status_
== DataTypeManager::ABORTED
&&
1474 expect_sync_configuration_aborted_
) {
1475 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1476 expect_sync_configuration_aborted_
= false;
1480 // Handle unrecoverable error.
1481 if (configure_status_
!= DataTypeManager::OK
) {
1482 // Something catastrophic had happened. We should only have one
1483 // error representing it.
1484 syncer::SyncError error
=
1485 data_type_status_table_
.GetUnrecoverableError();
1486 DCHECK(error
.IsSet());
1487 std::string message
=
1488 "Sync configuration failed with status " +
1489 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1491 syncer::ModelTypeSetToString(
1492 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1493 ": " + error
.message();
1494 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1495 OnInternalUnrecoverableError(error
.location(),
1498 ERROR_REASON_CONFIGURATION_FAILURE
);
1502 // We should never get in a state where we have no encrypted datatypes
1503 // enabled, and yet we still think we require a passphrase for decryption.
1504 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1505 !IsEncryptedDatatypeEnabled()));
1507 // This must be done before we start syncing with the server to avoid
1508 // sending unencrypted data up on a first time sync.
1509 if (encryption_pending_
)
1510 backend_
->EnableEncryptEverything();
1513 if (migrator_
.get() &&
1514 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1515 // Migration in progress. Let the migrator know we just finished
1516 // configuring something. It will be up to the migrator to call
1517 // StartSyncingWithServer() if migration is now finished.
1518 migrator_
->OnConfigureDone(result
);
1520 StartSyncingWithServer();
1524 void ProfileSyncService::OnConfigureStart() {
1525 sync_configure_start_time_
= base::Time::Now();
1529 ProfileSyncService::SyncStatusSummary
1530 ProfileSyncService::QuerySyncStatusSummary() {
1531 if (HasUnrecoverableError()) {
1532 return UNRECOVERABLE_ERROR
;
1533 } else if (!backend_
) {
1535 } else if (backend_mode_
== BACKUP
) {
1536 return BACKUP_USER_DATA
;
1537 } else if (backend_mode_
== ROLLBACK
) {
1538 return ROLLBACK_USER_DATA
;
1539 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1540 return SETUP_INCOMPLETE
;
1542 backend_
.get() && HasSyncSetupCompleted() &&
1543 directory_data_type_manager_
.get() &&
1544 directory_data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1545 return DATATYPES_NOT_INITIALIZED
;
1546 } else if (IsSyncActive()) {
1549 return UNKNOWN_ERROR
;
1552 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1553 SyncStatusSummary status
= QuerySyncStatusSummary();
1555 std::string config_status_str
=
1556 configure_status_
!= DataTypeManager::UNKNOWN
?
1557 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1560 case UNRECOVERABLE_ERROR
:
1561 return "Unrecoverable error detected";
1563 return "Syncing not enabled";
1564 case SETUP_INCOMPLETE
:
1565 return "First time sync setup incomplete";
1566 case DATATYPES_NOT_INITIALIZED
:
1567 return "Datatypes not fully initialized";
1569 return "Sync service initialized";
1570 case BACKUP_USER_DATA
:
1571 return "Backing-up user data. Status: " + config_status_str
;
1572 case ROLLBACK_USER_DATA
:
1573 return "Restoring user data. Status: " + config_status_str
;
1575 return "Status unknown: Internal error?";
1579 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1580 return startup_controller_
->GetBackendInitializationStateString();
1583 bool ProfileSyncService::auto_start_enabled() const {
1584 return startup_controller_
->auto_start_enabled();
1587 bool ProfileSyncService::setup_in_progress() const {
1588 return startup_controller_
->setup_in_progress();
1591 bool ProfileSyncService::QueryDetailedSyncStatus(
1592 SyncBackendHost::Status
* result
) {
1593 if (backend_
.get() && backend_initialized_
) {
1594 *result
= backend_
->GetDetailedStatus();
1597 SyncBackendHost::Status status
;
1598 status
.sync_protocol_error
= last_actionable_error_
;
1604 const AuthError
& ProfileSyncService::GetAuthError() const {
1605 return last_auth_error_
;
1608 bool ProfileSyncService::FirstSetupInProgress() const {
1609 return !HasSyncSetupCompleted() && startup_controller_
->setup_in_progress();
1612 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1613 // This method is a no-op if |setup_in_progress_| remains unchanged.
1614 if (startup_controller_
->setup_in_progress() == setup_in_progress
)
1617 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1618 if (!setup_in_progress
&& backend_initialized())
1619 ReconfigureDatatypeManager();
1623 bool ProfileSyncService::IsSyncAllowed() const {
1624 return IsSyncAllowedByFlag() && !IsManaged();
1627 bool ProfileSyncService::IsSyncActive() const {
1628 return backend_initialized_
&& backend_mode_
== SYNC
&&
1629 directory_data_type_manager_
&&
1630 directory_data_type_manager_
->state() != DataTypeManager::STOPPED
;
1633 bool ProfileSyncService::IsSignedIn() const {
1634 // Sync is logged in if there is a non-empty effective account id.
1635 return !signin_
->GetAccountIdToUse().empty();
1638 bool ProfileSyncService::backend_initialized() const {
1639 return backend_initialized_
;
1642 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1643 return backend_mode_
;
1646 bool ProfileSyncService::ConfigurationDone() const {
1647 return directory_data_type_manager_
&&
1648 directory_data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1651 bool ProfileSyncService::waiting_for_auth() const {
1652 return is_auth_in_progress_
;
1655 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1656 return current_experiments_
;
1659 bool ProfileSyncService::HasUnrecoverableError() const {
1660 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1663 bool ProfileSyncService::IsPassphraseRequired() const {
1664 return passphrase_required_reason_
!=
1665 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1668 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1669 // If there is an encrypted datatype enabled and we don't have the proper
1670 // passphrase, we must prompt the user for a passphrase. The only way for the
1671 // user to avoid entering their passphrase is to disable the encrypted types.
1672 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1675 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1676 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1677 if (last_synced_time
.is_null())
1678 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1680 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1682 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1683 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1685 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1686 ui::TimeFormat::LENGTH_SHORT
,
1687 time_since_last_sync
);
1690 void ProfileSyncService::UpdateSelectedTypesHistogram(
1691 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1692 if (!HasSyncSetupCompleted() ||
1693 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1694 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1697 // Only log the data types that are shown in the sync settings ui.
1698 // Note: the order of these types must match the ordering of
1699 // the respective types in ModelType
1700 const sync_driver::user_selectable_type::UserSelectableSyncType
1701 user_selectable_types
[] = {
1702 sync_driver::user_selectable_type::BOOKMARKS
,
1703 sync_driver::user_selectable_type::PREFERENCES
,
1704 sync_driver::user_selectable_type::PASSWORDS
,
1705 sync_driver::user_selectable_type::AUTOFILL
,
1706 sync_driver::user_selectable_type::THEMES
,
1707 sync_driver::user_selectable_type::TYPED_URLS
,
1708 sync_driver::user_selectable_type::EXTENSIONS
,
1709 sync_driver::user_selectable_type::APPS
,
1710 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1711 sync_driver::user_selectable_type::PROXY_TABS
,
1714 static_assert(36 == syncer::MODEL_TYPE_COUNT
,
1715 "custom config histogram must be updated");
1717 if (!sync_everything
) {
1718 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1720 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1721 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1723 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1725 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1727 const syncer::ModelType type
= it
.Get();
1728 if (chosen_types
.Has(type
) &&
1729 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1730 // Selected type has changed - log it.
1731 UMA_HISTOGRAM_ENUMERATION(
1733 user_selectable_types
[i
],
1734 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1740 #if defined(OS_CHROMEOS)
1741 void ProfileSyncService::RefreshSpareBootstrapToken(
1742 const std::string
& passphrase
) {
1743 sync_driver::SystemEncryptor encryptor
;
1744 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1745 // The first 2 params (hostname and username) doesn't have any effect here.
1746 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1748 std::string bootstrap_token
;
1749 if (!temp_cryptographer
.AddKey(key_params
)) {
1750 NOTREACHED() << "Failed to add key to cryptographer.";
1752 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1753 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1757 void ProfileSyncService::OnUserChoseDatatypes(
1758 bool sync_everything
,
1759 syncer::ModelTypeSet chosen_types
) {
1760 if (!backend_
.get() && !HasUnrecoverableError()) {
1765 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1766 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1768 if (directory_data_type_manager_
.get())
1769 directory_data_type_manager_
->ResetDataTypeErrors();
1770 ChangePreferredDataTypes(chosen_types
);
1773 void ProfileSyncService::ChangePreferredDataTypes(
1774 syncer::ModelTypeSet preferred_types
) {
1776 DVLOG(1) << "ChangePreferredDataTypes invoked";
1777 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1778 const syncer::ModelTypeSet registered_preferred_types
=
1779 Intersection(registered_types
, preferred_types
);
1780 sync_prefs_
.SetPreferredDataTypes(registered_types
,
1781 registered_preferred_types
);
1783 // Now reconfigure the DTM.
1784 ReconfigureDatatypeManager();
1786 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1787 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1788 // which types should be enabled and when.
1791 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1792 if (!IsSyncActive() || !ConfigurationDone())
1793 return syncer::ModelTypeSet();
1794 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1795 const syncer::ModelTypeSet failed_types
=
1796 data_type_status_table_
.GetFailedTypes();
1797 return Difference(preferred_types
, failed_types
);
1800 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1801 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1802 const syncer::ModelTypeSet preferred_types
=
1803 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1804 const syncer::ModelTypeSet enforced_types
=
1805 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1806 return Union(preferred_types
, enforced_types
);
1809 syncer::ModelTypeSet
1810 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1811 const syncer::ModelTypeSet registered_directory_types
=
1812 GetRegisteredDirectoryDataTypes();
1813 const syncer::ModelTypeSet preferred_types
=
1814 sync_prefs_
.GetPreferredDataTypes(registered_directory_types
);
1815 const syncer::ModelTypeSet enforced_types
=
1816 Intersection(GetDataTypesFromPreferenceProviders(),
1817 registered_directory_types
);
1818 return Union(preferred_types
, enforced_types
);
1821 syncer::ModelTypeSet
1822 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1823 return sync_prefs_
.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1826 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1827 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1828 // we'll need another way to distinguish user-choosable types from
1829 // programmatically-enabled types.
1830 return GetDataTypesFromPreferenceProviders();
1833 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1834 return Union(GetRegisteredDirectoryDataTypes(),
1835 GetRegisteredNonBlockingDataTypes());
1838 syncer::ModelTypeSet
1839 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1840 syncer::ModelTypeSet registered_types
;
1841 // The directory_data_type_controllers_ are determined by command-line flags;
1842 // that's effectively what controls the values returned here.
1843 for (DataTypeController::TypeMap::const_iterator it
=
1844 directory_data_type_controllers_
.begin();
1845 it
!= directory_data_type_controllers_
.end(); ++it
) {
1846 registered_types
.Put(it
->first
);
1848 return registered_types
;
1851 syncer::ModelTypeSet
1852 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1853 return non_blocking_data_type_manager_
.GetRegisteredTypes();
1856 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1857 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1858 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1859 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1862 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1863 return backend_
->GetPassphraseType();
1866 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1867 return backend_
->GetExplicitPassphraseTime();
1870 bool ProfileSyncService::IsCryptographerReady(
1871 const syncer::BaseTransaction
* trans
) const {
1872 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1875 void ProfileSyncService::ConfigurePriorityDataTypes() {
1876 const syncer::ModelTypeSet priority_types
=
1877 Intersection(GetPreferredDirectoryDataTypes(),
1878 syncer::PriorityUserTypes());
1879 if (!priority_types
.Empty()) {
1880 const syncer::ConfigureReason reason
= HasSyncSetupCompleted() ?
1881 syncer::CONFIGURE_REASON_RECONFIGURATION
:
1882 syncer::CONFIGURE_REASON_NEW_CLIENT
;
1883 directory_data_type_manager_
->Configure(priority_types
, reason
);
1887 void ProfileSyncService::ConfigureDataTypeManager() {
1888 // Don't configure datatypes if the setup UI is still on the screen - this
1889 // is to help multi-screen setting UIs (like iOS) where they don't want to
1890 // start syncing data until the user is done configuring encryption options,
1891 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1892 // SetSetupInProgress(false).
1893 if (backend_mode_
== SYNC
&& startup_controller_
->setup_in_progress())
1896 bool restart
= false;
1897 if (!directory_data_type_manager_
) {
1899 directory_data_type_manager_
.reset(
1900 factory_
->CreateDataTypeManager(debug_info_listener_
,
1901 &directory_data_type_controllers_
,
1906 // We create the migrator at the same time.
1908 new browser_sync::BackendMigrator(
1909 profile_
->GetDebugName(), GetUserShare(),
1910 this, directory_data_type_manager_
.get(),
1911 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1912 base::Unretained(this))));
1915 syncer::ModelTypeSet types
;
1916 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1917 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1918 types
= syncer::BackupTypes();
1919 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1921 types
= GetPreferredDirectoryDataTypes();
1922 if (!HasSyncSetupCompleted()) {
1923 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1924 } else if (restart
) {
1925 // Datatype downloads on restart are generally due to newly supported
1926 // datatypes (although it's also possible we're picking up where a failed
1927 // previous configuration left off).
1928 // TODO(sync): consider detecting configuration recovery and setting
1929 // the reason here appropriately.
1930 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1932 // The user initiated a reconfiguration (either to add or remove types).
1933 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1937 directory_data_type_manager_
->Configure(types
, reason
);
1940 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1941 if (backend_
.get() && backend_initialized_
) {
1942 return backend_
->GetUserShare();
1948 syncer::sessions::SyncSessionSnapshot
1949 ProfileSyncService::GetLastSessionSnapshot() const {
1951 return backend_
->GetLastSessionSnapshot();
1952 return syncer::sessions::SyncSessionSnapshot();
1955 bool ProfileSyncService::HasUnsyncedItems() const {
1956 if (HasSyncingBackend() && backend_initialized_
) {
1957 return backend_
->HasUnsyncedItems();
1963 browser_sync::BackendMigrator
*
1964 ProfileSyncService::GetBackendMigratorForTest() {
1965 return migrator_
.get();
1968 void ProfileSyncService::GetModelSafeRoutingInfo(
1969 syncer::ModelSafeRoutingInfo
* out
) const {
1970 if (backend_
.get() && backend_initialized_
) {
1971 backend_
->GetModelSafeRoutingInfo(out
);
1977 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
1978 scoped_ptr
<base::ListValue
> result(new base::ListValue());
1980 if (!backend_
.get() || !backend_initialized_
) {
1981 return result
.release();
1984 DataTypeStatusTable::TypeErrorMap error_map
=
1985 data_type_status_table_
.GetAllErrors();
1986 ModelTypeSet active_types
;
1987 ModelTypeSet passive_types
;
1988 ModelSafeRoutingInfo routing_info
;
1989 backend_
->GetModelSafeRoutingInfo(&routing_info
);
1990 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
1991 it
!= routing_info
.end(); ++it
) {
1992 if (it
->second
== syncer::GROUP_PASSIVE
) {
1993 passive_types
.Put(it
->first
);
1995 active_types
.Put(it
->first
);
1999 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2000 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2001 ModelTypeSet registered
= GetRegisteredDataTypes();
2002 scoped_ptr
<base::DictionaryValue
> type_status_header(
2003 new base::DictionaryValue());
2005 type_status_header
->SetString("name", "Model Type");
2006 type_status_header
->SetString("status", "header");
2007 type_status_header
->SetString("value", "Group Type");
2008 type_status_header
->SetString("num_entries", "Total Entries");
2009 type_status_header
->SetString("num_live", "Live Entries");
2010 result
->Append(type_status_header
.release());
2012 scoped_ptr
<base::DictionaryValue
> type_status
;
2013 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2014 ModelType type
= it
.Get();
2016 type_status
.reset(new base::DictionaryValue());
2017 type_status
->SetString("name", ModelTypeToString(type
));
2019 if (error_map
.find(type
) != error_map
.end()) {
2020 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2021 DCHECK(error
.IsSet());
2022 switch (error
.GetSeverity()) {
2023 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2024 std::string error_text
= "Error: " + error
.location().ToString() +
2025 ", " + error
.GetMessagePrefix() + error
.message();
2026 type_status
->SetString("status", "error");
2027 type_status
->SetString("value", error_text
);
2030 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2031 type_status
->SetString("status", "disabled");
2032 type_status
->SetString("value", error
.message());
2035 NOTREACHED() << "Unexpected error severity.";
2038 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2039 // Show a proxy type in "ok" state unless it is disabled by user.
2040 DCHECK(!throttled_types
.Has(type
));
2041 type_status
->SetString("status", "ok");
2042 type_status
->SetString("value", "Passive");
2043 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2044 type_status
->SetString("status", "warning");
2045 type_status
->SetString("value", "Passive, Throttled");
2046 } else if (passive_types
.Has(type
)) {
2047 type_status
->SetString("status", "warning");
2048 type_status
->SetString("value", "Passive");
2049 } else if (throttled_types
.Has(type
)) {
2050 type_status
->SetString("status", "warning");
2051 type_status
->SetString("value", "Throttled");
2052 } else if (GetRegisteredNonBlockingDataTypes().Has(type
)) {
2053 type_status
->SetString("status", "ok");
2054 type_status
->SetString("value", "Non-Blocking");
2055 } else if (active_types
.Has(type
)) {
2056 type_status
->SetString("status", "ok");
2057 type_status
->SetString("value", "Active: " +
2058 ModelSafeGroupToString(routing_info
[type
]));
2060 type_status
->SetString("status", "warning");
2061 type_status
->SetString("value", "Disabled by User");
2064 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2065 detailed_status
.num_to_delete_entries_by_type
[type
];
2066 type_status
->SetInteger("num_entries",
2067 detailed_status
.num_entries_by_type
[type
]);
2068 type_status
->SetInteger("num_live", live_count
);
2070 result
->Append(type_status
.release());
2072 return result
.release();
2075 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2078 backend_
->DeactivateDataType(type
);
2081 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2082 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2083 // If the backend isn't running yet, OnBackendInitialized() will call this
2084 // method again after the backend starts up.
2085 if (cached_passphrase_
.empty() || !backend_initialized())
2088 // Backend is up and running, so we can consume the cached passphrase.
2089 std::string passphrase
= cached_passphrase_
;
2090 cached_passphrase_
.clear();
2092 // If we need a passphrase to decrypt data, try the cached passphrase.
2093 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2094 if (SetDecryptionPassphrase(passphrase
)) {
2095 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2100 // If we get here, we don't have pending keys (or at least, the passphrase
2101 // doesn't decrypt them) - just try to re-encrypt using the encryption
2103 if (!IsUsingSecondaryPassphrase())
2104 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2107 void ProfileSyncService::RequestAccessToken() {
2108 // Only one active request at a time.
2109 if (access_token_request_
!= NULL
)
2111 request_access_token_retry_timer_
.Stop();
2112 OAuth2TokenService::ScopeSet oauth2_scopes
;
2113 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2115 // Invalidate previous token, otherwise token service will return the same
2117 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2118 if (!access_token_
.empty()) {
2119 oauth2_token_service_
->InvalidateToken(
2120 account_id
, oauth2_scopes
, access_token_
);
2123 access_token_
.clear();
2125 token_request_time_
= base::Time::Now();
2126 token_receive_time_
= base::Time();
2127 next_token_request_time_
= base::Time();
2128 access_token_request_
=
2129 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2132 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2133 PassphraseType type
) {
2134 // This should only be called when the backend has been initialized.
2135 DCHECK(backend_initialized());
2136 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2137 "Data is already encrypted using an explicit passphrase";
2138 DCHECK(!(type
== EXPLICIT
&&
2139 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2140 "Can not set explicit passphrase when decryption is needed.";
2142 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2143 << " passphrase for encryption.";
2144 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2145 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2146 // keys. Hence, as long as we're not trying to do an invalid passphrase
2147 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2148 // will succeed. If for some reason a new encryption key arrives via
2149 // sync later, the SBH will trigger another OnPassphraseRequired().
2150 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2153 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2156 bool ProfileSyncService::SetDecryptionPassphrase(
2157 const std::string
& passphrase
) {
2158 if (IsPassphraseRequired()) {
2159 DVLOG(1) << "Setting passphrase for decryption.";
2160 bool result
= backend_
->SetDecryptionPassphrase(passphrase
);
2161 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result
);
2164 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2165 "IsPassphraseRequired() is false.";
2170 bool ProfileSyncService::EncryptEverythingAllowed() const {
2171 return encrypt_everything_allowed_
;
2174 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2175 DCHECK(allowed
|| !backend_initialized() || !EncryptEverythingEnabled());
2176 encrypt_everything_allowed_
= allowed
;
2179 void ProfileSyncService::EnableEncryptEverything() {
2180 DCHECK(EncryptEverythingAllowed());
2182 // Tests override backend_initialized() to always return true, so we
2183 // must check that instead of |backend_initialized_|.
2184 // TODO(akalin): Fix the above. :/
2185 DCHECK(backend_initialized());
2186 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2187 // problems around cancelling encryption in the background (crbug.com/119649).
2188 if (!encrypt_everything_
)
2189 encryption_pending_
= true;
2192 bool ProfileSyncService::encryption_pending() const {
2193 // We may be called during the setup process before we're
2194 // initialized (via IsEncryptedDatatypeEnabled and
2195 // IsPassphraseRequiredForDecryption).
2196 return encryption_pending_
;
2199 bool ProfileSyncService::EncryptEverythingEnabled() const {
2200 DCHECK(backend_initialized_
);
2201 return encrypt_everything_
|| encryption_pending_
;
2204 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2205 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2206 // We may be called during the setup process before we're
2207 // initialized. In this case, we default to the sensitive types.
2208 return encrypted_types_
;
2211 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2212 if (is_sync_managed
) {
2215 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2216 startup_controller_
->TryStart();
2220 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2221 const std::string
& username
,
2222 const std::string
& password
) {
2223 if (IsSyncRequested() && !password
.empty()) {
2224 cached_passphrase_
= password
;
2225 // Try to consume the passphrase we just cached. If the sync backend
2226 // is not running yet, the passphrase will remain cached until the
2227 // backend starts up.
2228 ConsumeCachedPassphraseIfPossible();
2230 #if defined(OS_CHROMEOS)
2231 RefreshSpareBootstrapToken(password
);
2233 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE
) {
2234 // Track the fact that we're still waiting for auth to complete.
2235 is_auth_in_progress_
= true;
2239 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2240 const std::string
& username
) {
2241 sync_disabled_by_admin_
= false;
2244 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2245 need_backup_
= true;
2246 backup_finished_
= false;
2250 void ProfileSyncService::AddObserver(
2251 sync_driver::SyncServiceObserver
* observer
) {
2252 observers_
.AddObserver(observer
);
2255 void ProfileSyncService::RemoveObserver(
2256 sync_driver::SyncServiceObserver
* observer
) {
2257 observers_
.RemoveObserver(observer
);
2260 void ProfileSyncService::AddProtocolEventObserver(
2261 browser_sync::ProtocolEventObserver
* observer
) {
2262 protocol_event_observers_
.AddObserver(observer
);
2263 if (HasSyncingBackend()) {
2264 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2268 void ProfileSyncService::RemoveProtocolEventObserver(
2269 browser_sync::ProtocolEventObserver
* observer
) {
2270 protocol_event_observers_
.RemoveObserver(observer
);
2271 if (HasSyncingBackend() &&
2272 !protocol_event_observers_
.might_have_observers()) {
2273 backend_
->DisableProtocolEventForwarding();
2277 void ProfileSyncService::AddTypeDebugInfoObserver(
2278 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2279 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2280 if (type_debug_info_observers_
.might_have_observers() &&
2281 backend_initialized_
) {
2282 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2286 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2287 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2288 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2289 if (!type_debug_info_observers_
.might_have_observers() &&
2290 backend_initialized_
) {
2291 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2295 void ProfileSyncService::AddPreferenceProvider(
2296 SyncTypePreferenceProvider
* provider
) {
2297 DCHECK(!HasPreferenceProvider(provider
))
2298 << "Providers may only be added once!";
2299 preference_providers_
.insert(provider
);
2302 void ProfileSyncService::RemovePreferenceProvider(
2303 SyncTypePreferenceProvider
* provider
) {
2304 DCHECK(HasPreferenceProvider(provider
))
2305 << "Only providers that have been added before can be removed!";
2306 preference_providers_
.erase(provider
);
2309 bool ProfileSyncService::HasPreferenceProvider(
2310 SyncTypePreferenceProvider
* provider
) const {
2311 return preference_providers_
.count(provider
) > 0;
2316 class GetAllNodesRequestHelper
2317 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2319 GetAllNodesRequestHelper(
2320 syncer::ModelTypeSet requested_types
,
2321 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2323 void OnReceivedNodesForTypes(
2324 const std::vector
<syncer::ModelType
>& types
,
2325 ScopedVector
<base::ListValue
> scoped_node_lists
);
2328 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2329 virtual ~GetAllNodesRequestHelper();
2331 scoped_ptr
<base::ListValue
> result_accumulator_
;
2333 syncer::ModelTypeSet awaiting_types_
;
2334 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2337 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2338 syncer::ModelTypeSet requested_types
,
2339 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2340 : result_accumulator_(new base::ListValue()),
2341 awaiting_types_(requested_types
),
2342 callback_(callback
) {}
2344 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2345 if (!awaiting_types_
.Empty()) {
2347 << "GetAllNodesRequest deleted before request was fulfilled. "
2348 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2352 // Called when the set of nodes for a type or set of types has been returned.
2354 // The nodes for several types can be returned at the same time by specifying
2355 // their types in the |types| array, and putting their results at the
2356 // correspnding indices in the |scoped_node_lists|.
2357 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2358 const std::vector
<syncer::ModelType
>& types
,
2359 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2360 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2362 // Take unsafe ownership of the node list.
2363 std::vector
<base::ListValue
*> node_lists
;
2364 scoped_node_lists
.release(&node_lists
);
2366 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2367 const ModelType type
= types
[i
];
2368 base::ListValue
* node_list
= node_lists
[i
];
2370 // Add these results to our list.
2371 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2372 type_dict
->SetString("type", ModelTypeToString(type
));
2373 type_dict
->Set("nodes", node_list
);
2374 result_accumulator_
->Append(type_dict
.release());
2376 // Remember that this part of the request is satisfied.
2377 awaiting_types_
.Remove(type
);
2380 if (awaiting_types_
.Empty()) {
2381 callback_
.Run(result_accumulator_
.Pass());
2388 void ProfileSyncService::GetAllNodes(
2389 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2390 ModelTypeSet directory_types
= GetRegisteredDirectoryDataTypes();
2391 directory_types
.PutAll(syncer::ControlTypes());
2392 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2393 new GetAllNodesRequestHelper(directory_types
, callback
);
2395 if (!backend_initialized_
) {
2396 // If there's no backend available to fulfill the request, handle it here.
2397 ScopedVector
<base::ListValue
> empty_results
;
2398 std::vector
<ModelType
> type_vector
;
2399 for (ModelTypeSet::Iterator it
= directory_types
.First();
2400 it
.Good(); it
.Inc()) {
2401 type_vector
.push_back(it
.Get());
2402 empty_results
.push_back(new base::ListValue());
2404 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2406 backend_
->GetAllNodesForTypes(
2408 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2412 bool ProfileSyncService::HasObserver(
2413 const sync_driver::SyncServiceObserver
* observer
) const {
2414 return observers_
.HasObserver(observer
);
2417 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2418 return sync_js_controller_
.AsWeakPtr();
2421 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2422 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2426 bool ProfileSyncService::IsSyncAllowedByFlag() {
2427 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2428 switches::kDisableSync
);
2431 bool ProfileSyncService::IsManaged() const {
2432 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2435 void ProfileSyncService::RequestStop() {
2436 sync_prefs_
.SetSyncRequested(false);
2437 if (HasSyncingBackend()) {
2438 backend_
->UnregisterInvalidationIds();
2440 ShutdownImpl(syncer::STOP_SYNC
);
2443 bool ProfileSyncService::IsSyncRequested() const {
2444 return sync_prefs_
.IsSyncRequested();
2447 SigninManagerBase
* ProfileSyncService::signin() const {
2450 return signin_
->GetOriginal();
2453 void ProfileSyncService::RequestStart() {
2455 sync_prefs_
.SetSyncRequested(true);
2456 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2457 startup_controller_
->TryStart();
2460 void ProfileSyncService::ReconfigureDatatypeManager() {
2461 // If we haven't initialized yet, don't configure the DTM as it could cause
2462 // association to start before a Directory has even been created.
2463 if (backend_initialized_
) {
2464 DCHECK(backend_
.get());
2465 ConfigureDataTypeManager();
2466 } else if (HasUnrecoverableError()) {
2467 // There is nothing more to configure. So inform the listeners,
2470 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2471 << "Unrecoverable error.";
2473 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2478 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2480 syncer::ModelTypeSet types
;
2481 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2482 preference_providers_
.begin();
2483 it
!= preference_providers_
.end();
2485 types
.PutAll((*it
)->GetPreferredDataTypes());
2490 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2492 return data_type_status_table_
;
2495 void ProfileSyncService::OnInternalUnrecoverableError(
2496 const tracked_objects::Location
& from_here
,
2497 const std::string
& message
,
2498 bool delete_sync_database
,
2499 UnrecoverableErrorReason reason
) {
2500 DCHECK(!HasUnrecoverableError());
2501 unrecoverable_error_reason_
= reason
;
2502 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2505 syncer::SyncManagerFactory::MANAGER_TYPE
2506 ProfileSyncService::GetManagerType() const {
2507 switch (backend_mode_
) {
2509 return syncer::SyncManagerFactory::NORMAL
;
2511 return syncer::SyncManagerFactory::BACKUP
;
2513 return syncer::SyncManagerFactory::ROLLBACK
;
2517 return syncer::SyncManagerFactory::NORMAL
;
2520 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2521 return request_access_token_retry_timer_
.IsRunning();
2524 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2525 return access_token_
;
2528 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2529 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2532 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2533 return sessions_sync_manager_
.get();
2536 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2537 return device_info_sync_service_
.get();
2540 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2541 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED
),
2542 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2543 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2545 ProfileSyncService::SyncTokenStatus
2546 ProfileSyncService::GetSyncTokenStatus() const {
2547 SyncTokenStatus status
;
2548 status
.connection_status_update_time
= connection_status_update_time_
;
2549 status
.connection_status
= connection_status_
;
2550 status
.token_request_time
= token_request_time_
;
2551 status
.token_receive_time
= token_receive_time_
;
2552 status
.last_get_token_error
= last_get_token_error_
;
2553 if (request_access_token_retry_timer_
.IsRunning())
2554 status
.next_token_request_time
= next_token_request_time_
;
2558 void ProfileSyncService::OverrideNetworkResourcesForTest(
2559 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2560 network_resources_
= network_resources
.Pass();
2563 bool ProfileSyncService::HasSyncingBackend() const {
2564 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2567 void ProfileSyncService::UpdateFirstSyncTimePref() {
2568 if (!IsSignedIn()) {
2569 // Clear if user's not signed in and rollback is done.
2570 if (backend_mode_
!= ROLLBACK
)
2571 sync_prefs_
.ClearFirstSyncTime();
2572 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2573 backend_mode_
== SYNC
) {
2574 // Set if not set before and it's syncing now.
2575 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2579 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2580 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2581 if (first_sync_time
.is_null())
2584 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2590 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2591 BrowsingDataRemover::Observer
* observer
) {
2592 browsing_data_remover_observer_
= observer
;
2595 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2596 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2600 clear_browsing_data_
= c
;
2603 GURL
ProfileSyncService::GetSyncServiceURL(
2604 const base::CommandLine
& command_line
) {
2605 // By default, dev, canary, and unbranded Chromium users will go to the
2606 // development servers. Development servers have more features than standard
2607 // sync servers. Users with officially-branded Chrome stable and beta builds
2608 // will go to the standard sync servers.
2609 GURL
result(kDevServerUrl
);
2611 chrome::VersionInfo::Channel channel
= chrome::VersionInfo::GetChannel();
2612 if (channel
== chrome::VersionInfo::CHANNEL_STABLE
||
2613 channel
== chrome::VersionInfo::CHANNEL_BETA
) {
2614 result
= GURL(kSyncServerUrl
);
2617 // Override the sync server URL from the command-line, if sync server
2618 // command-line argument exists.
2619 if (command_line
.HasSwitch(switches::kSyncServiceURL
)) {
2620 std::string
value(command_line
.GetSwitchValueASCII(
2621 switches::kSyncServiceURL
));
2622 if (!value
.empty()) {
2623 GURL
custom_sync_url(value
);
2624 if (custom_sync_url
.is_valid()) {
2625 result
= custom_sync_url
;
2627 LOG(WARNING
) << "The following sync URL specified at the command-line "
2628 << "is invalid: " << value
;
2635 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2636 DCHECK_EQ(backend_mode_
, SYNC
);
2638 #if defined(ENABLE_PRE_SYNC_BACKUP)
2639 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2640 // Check backup once a day.
2641 if (!last_backup_time_
&&
2642 (last_synced_time
.is_null() ||
2643 base::Time::Now() - last_synced_time
>=
2644 base::TimeDelta::FromDays(1))) {
2645 // If sync thread is set, need to serialize check on sync thread after
2646 // closing backup DB.
2648 sync_thread_
->message_loop_proxy()->PostTask(
2650 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2651 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2652 base::ThreadTaskRunnerHandle::Get(),
2653 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2654 weak_factory_
.GetWeakPtr())));
2656 content::BrowserThread::PostTask(
2657 content::BrowserThread::FILE, FROM_HERE
,
2658 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2659 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2660 base::ThreadTaskRunnerHandle::Get(),
2661 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2662 weak_factory_
.GetWeakPtr())));
2668 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2669 last_backup_time_
.reset(new base::Time(backup_time
));
2671 DCHECK(device_info_sync_service_
);
2672 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2675 void ProfileSyncService::TryStartSyncAfterBackup() {
2676 startup_controller_
->Reset(GetRegisteredDataTypes());
2677 startup_controller_
->TryStart();
2680 void ProfileSyncService::CleanUpBackup() {
2681 sync_prefs_
.ClearFirstSyncTime();
2682 profile_
->GetIOTaskRunner()->PostTask(
2684 base::Bind(base::IgnoreResult(base::DeleteFile
),
2685 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2689 bool ProfileSyncService::NeedBackup() const {
2690 return need_backup_
;
2693 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2694 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2697 void ProfileSyncService::FlushDirectory() const {
2698 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2699 // If sync is not initialized yet, we fail silently.
2700 if (backend_initialized_
)
2701 backend_
->FlushDirectory();
2704 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2705 return directory_path_
;
2708 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2710 return sync_thread_
->message_loop();
2711 } else if (backend_
) {
2712 return backend_
->GetSyncLoopForTesting();
2718 void ProfileSyncService::RemoveClientFromServer() const {
2719 if (!backend_initialized_
) return;
2720 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2721 std::string birthday
;
2722 syncer::UserShare
* user_share
= GetUserShare();
2723 if (user_share
&& user_share
->directory
.get()) {
2724 birthday
= user_share
->directory
->store_birthday();
2726 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2727 sync_stopped_reporter_
->ReportSyncStopped(
2728 access_token_
, cache_guid
, birthday
);
2732 void ProfileSyncService::OnMemoryPressure(
2733 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
2734 if (memory_pressure_level
==
2735 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
2736 sync_prefs_
.SetMemoryPressureWarningCount(
2737 sync_prefs_
.GetMemoryPressureWarningCount() + 1);
2741 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2742 int warning_received
= sync_prefs_
.GetMemoryPressureWarningCount();
2744 if (-1 != warning_received
) {
2745 // -1 means it is new client.
2746 if (!sync_prefs_
.DidSyncShutdownCleanly()) {
2747 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2750 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2754 sync_prefs_
.SetMemoryPressureWarningCount(0);
2755 // Will set to true during a clean shutdown, so crash or something else will
2756 // remain this as false.
2757 sync_prefs_
.SetCleanShutdown(false);