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/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/single_thread_task_runner.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/glue/chrome_report_unrecoverable_error.h"
43 #include "chrome/browser/sync/glue/favicon_cache.h"
44 #include "chrome/browser/sync/glue/sync_backend_host.h"
45 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
46 #include "chrome/browser/sync/glue/sync_start_util.h"
47 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
48 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
49 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
50 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
51 #include "chrome/browser/sync/sync_type_preference_provider.h"
52 #include "chrome/browser/ui/browser.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_window.h"
55 #include "chrome/browser/ui/global_error/global_error_service.h"
56 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
57 #include "chrome/common/chrome_switches.h"
58 #include "chrome/common/pref_names.h"
59 #include "chrome/common/sync_util.h"
60 #include "chrome/common/url_constants.h"
61 #include "chrome/grit/generated_resources.h"
62 #include "components/autofill/core/common/autofill_pref_names.h"
63 #include "components/invalidation/impl/profile_invalidation_provider.h"
64 #include "components/invalidation/public/invalidation_service.h"
65 #include "components/password_manager/core/browser/password_store.h"
66 #include "components/pref_registry/pref_registry_syncable.h"
67 #include "components/signin/core/browser/about_signin_internals.h"
68 #include "components/signin/core/browser/profile_oauth2_token_service.h"
69 #include "components/signin/core/browser/signin_manager.h"
70 #include "components/signin/core/browser/signin_metrics.h"
71 #include "components/sync_driver/backend_migrator.h"
72 #include "components/sync_driver/change_processor.h"
73 #include "components/sync_driver/data_type_controller.h"
74 #include "components/sync_driver/device_info.h"
75 #include "components/sync_driver/pref_names.h"
76 #include "components/sync_driver/sync_error_controller.h"
77 #include "components/sync_driver/sync_stopped_reporter.h"
78 #include "components/sync_driver/system_encryptor.h"
79 #include "components/sync_driver/user_selectable_sync_type.h"
80 #include "components/version_info/version_info_values.h"
81 #include "content/public/browser/browser_thread.h"
82 #include "content/public/browser/notification_details.h"
83 #include "content/public/browser/notification_service.h"
84 #include "content/public/browser/notification_source.h"
85 #include "net/cookies/cookie_monster.h"
86 #include "net/url_request/url_request_context_getter.h"
87 #include "sync/api/sync_error.h"
88 #include "sync/internal_api/public/configure_reason.h"
89 #include "sync/internal_api/public/http_bridge_network_resources.h"
90 #include "sync/internal_api/public/network_resources.h"
91 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
92 #include "sync/internal_api/public/shutdown_reason.h"
93 #include "sync/internal_api/public/sync_context_proxy.h"
94 #include "sync/internal_api/public/sync_encryption_handler.h"
95 #include "sync/internal_api/public/util/experiments.h"
96 #include "sync/internal_api/public/util/sync_db_util.h"
97 #include "sync/internal_api/public/util/sync_string_conversions.h"
98 #include "sync/js/js_event_details.h"
99 #include "sync/protocol/sync.pb.h"
100 #include "sync/syncable/directory.h"
101 #include "sync/util/cryptographer.h"
102 #include "ui/base/l10n/l10n_util.h"
103 #include "ui/base/l10n/time_format.h"
105 #if defined(OS_ANDROID)
106 #include "sync/internal_api/public/read_transaction.h"
109 using browser_sync::NotificationServiceSessionsRouter
;
110 using browser_sync::ProfileSyncServiceStartBehavior
;
111 using browser_sync::SessionsSyncManager
;
112 using browser_sync::SyncBackendHost
;
113 using sync_driver::ChangeProcessor
;
114 using sync_driver::DataTypeController
;
115 using sync_driver::DataTypeManager
;
116 using sync_driver::DataTypeStatusTable
;
117 using sync_driver::DeviceInfoSyncService
;
118 using syncer::ModelType
;
119 using syncer::ModelTypeSet
;
120 using syncer::JsBackend
;
121 using syncer::JsController
;
122 using syncer::JsEventDetails
;
123 using syncer::JsEventHandler
;
124 using syncer::ModelSafeRoutingInfo
;
125 using syncer::SyncCredentials
;
126 using syncer::SyncProtocolError
;
127 using syncer::WeakHandle
;
129 typedef GoogleServiceAuthError AuthError
;
131 const char kSyncUnrecoverableErrorHistogram
[] =
132 "Sync.UnrecoverableErrors";
134 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
135 // Number of initial errors (in sequence) to ignore before applying
136 // exponential back-off rules.
139 // Initial delay for exponential back-off in ms.
142 // Factor by which the waiting time will be multiplied.
145 // Fuzzing percentage. ex: 10% will spread requests randomly
146 // between 90%-100% of the calculated time.
149 // Maximum amount of time we are willing to delay our request in ms.
150 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
151 // RequestAccessToken on connection state change after backoff
152 1000 * 3600 * 4, // 4 hours.
154 // Time to keep an entry from being discarded even when it
155 // has no significant state, -1 to never discard.
158 // Don't use initial delay unless the last request was an error.
162 static const base::FilePath::CharType kSyncDataFolderName
[] =
163 FILE_PATH_LITERAL("Sync Data");
165 static const base::FilePath::CharType kSyncBackupDataFolderName
[] =
166 FILE_PATH_LITERAL("Sync Data Backup");
170 void ClearBrowsingData(BrowsingDataRemover::Observer
* observer
,
174 // BrowsingDataRemover deletes itself when it's done.
175 BrowsingDataRemover
* remover
= BrowsingDataRemover::CreateForRange(
176 profile
, start
, end
);
178 remover
->AddObserver(observer
);
179 remover
->Remove(BrowsingDataRemover::REMOVE_ALL
,
180 BrowsingDataHelper::ALL
);
182 scoped_refptr
<password_manager::PasswordStore
> password
=
183 PasswordStoreFactory::GetForProfile(profile
,
184 ServiceAccessType::EXPLICIT_ACCESS
);
185 password
->RemoveLoginsSyncedBetween(start
, end
);
188 // Perform the actual sync data folder deletion.
189 // This should only be called on the sync thread.
190 void DeleteSyncDataFolder(const base::FilePath
& directory_path
) {
191 if (base::DirectoryExists(directory_path
)) {
192 if (!base::DeleteFile(directory_path
, true))
193 LOG(DFATAL
) << "Could not delete the Sync Data folder.";
197 } // anonymous namespace
199 bool ShouldShowActionOnUI(
200 const syncer::SyncProtocolError
& error
) {
201 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
202 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
203 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
206 ProfileSyncService::ProfileSyncService(
207 scoped_ptr
<ProfileSyncComponentsFactory
> factory
,
209 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
210 ProfileOAuth2TokenService
* oauth2_token_service
,
211 ProfileSyncServiceStartBehavior start_behavior
)
212 : OAuth2TokenService::Consumer("sync"),
213 last_auth_error_(AuthError::AuthErrorNone()),
214 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
215 factory_(factory
.Pass()),
217 sync_prefs_(profile_
->GetPrefs()),
219 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
220 is_first_time_sync_configure_(false),
221 backend_initialized_(false),
222 sync_disabled_by_admin_(false),
223 is_auth_in_progress_(false),
224 signin_(signin_wrapper
.Pass()),
225 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
226 expect_sync_configuration_aborted_(false),
227 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
228 encrypt_everything_allowed_(true),
229 encrypt_everything_(false),
230 encryption_pending_(false),
231 configure_status_(DataTypeManager::UNKNOWN
),
232 oauth2_token_service_(oauth2_token_service
),
233 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
234 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
235 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
236 network_resources_(new syncer::HttpBridgeNetworkResources
),
239 backup_finished_(false),
240 clear_browsing_data_(base::Bind(&ClearBrowsingData
)),
241 browsing_data_remover_observer_(NULL
),
242 passphrase_prompt_triggered_by_version_(false),
244 startup_controller_weak_factory_(this) {
245 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
247 startup_controller_
.reset(new browser_sync::StartupController(
249 oauth2_token_service
,
252 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
253 startup_controller_weak_factory_
.GetWeakPtr(),
255 backup_rollback_controller_
.reset(new browser_sync::BackupRollbackController(
258 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
259 startup_controller_weak_factory_
.GetWeakPtr(),
261 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
262 startup_controller_weak_factory_
.GetWeakPtr(),
264 syncer::SyncableService::StartSyncFlare
flare(
265 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
266 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
267 new NotificationServiceSessionsRouter(profile
, flare
));
269 DCHECK(factory_
.get());
270 local_device_
= factory_
->CreateLocalDeviceInfoProvider();
271 sync_stopped_reporter_
.reset(
272 new browser_sync::SyncStoppedReporter(
274 local_device_
->GetSyncUserAgent(),
275 profile_
->GetRequestContext(),
276 browser_sync::SyncStoppedReporter::ResultCallback())),
277 sessions_sync_manager_
.reset(
278 new SessionsSyncManager(profile
, local_device_
.get(), router
.Pass()));
279 device_info_sync_service_
.reset(
280 new DeviceInfoSyncService(local_device_
.get()));
282 std::string last_version
= sync_prefs_
.GetLastRunVersion();
283 std::string current_version
= PRODUCT_VERSION
;
284 sync_prefs_
.SetLastRunVersion(current_version
);
286 // Check for a major version change. Note that the versions have format
287 // MAJOR.MINOR.BUILD.PATCH.
288 if (last_version
.substr(0, last_version
.find('.')) !=
289 current_version
.substr(0, current_version
.find('.'))) {
290 passphrase_prompt_triggered_by_version_
= true;
294 ProfileSyncService::~ProfileSyncService() {
295 sync_prefs_
.RemoveSyncPrefObserver(this);
296 // Shutdown() should have been called before destruction.
297 CHECK(!backend_initialized_
);
300 bool ProfileSyncService::CanSyncStart() const {
301 return IsSyncAllowed() && IsSyncRequested() && IsSignedIn();
304 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
305 if (!oauth2_token_service_
)
308 return oauth2_token_service_
->RefreshTokenIsAvailable(
309 signin_
->GetAccountIdToUse());
312 void ProfileSyncService::Initialize() {
313 // We clear this here (vs Shutdown) because we want to remember that an error
314 // happened on shutdown so we can display details (message, location) about it
318 sync_prefs_
.AddSyncPrefObserver(this);
320 // If sync isn't allowed, the only thing to do is to turn it off.
321 if (!IsSyncAllowed()) {
322 RequestStop(CLEAR_DATA
);
326 RegisterAuthNotifications();
328 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
329 // Clean up in case of previous crash / setup abort / signout.
330 StopImpl(CLEAR_DATA
);
333 TrySyncDatatypePrefRecovery();
335 #if defined(OS_CHROMEOS)
336 std::string bootstrap_token
= sync_prefs_
.GetEncryptionBootstrapToken();
337 if (bootstrap_token
.empty()) {
338 sync_prefs_
.SetEncryptionBootstrapToken(
339 sync_prefs_
.GetSpareBootstrapToken());
343 #if !defined(OS_ANDROID)
344 DCHECK(sync_error_controller_
== NULL
)
345 << "Initialize() called more than once.";
346 sync_error_controller_
.reset(new SyncErrorController(this));
347 AddObserver(sync_error_controller_
.get());
350 bool running_rollback
= false;
351 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
352 // Backup is needed if user's not signed in or signed in but previous
353 // backup didn't finish, i.e. backend didn't switch from backup to sync.
354 need_backup_
= !IsSignedIn() || sync_prefs_
.GetFirstSyncTime().is_null();
356 // Try to resume rollback if it didn't finish in last session.
357 running_rollback
= backup_rollback_controller_
->StartRollback();
359 need_backup_
= false;
362 #if defined(ENABLE_PRE_SYNC_BACKUP)
363 if (!running_rollback
&& !IsSignedIn()) {
367 DCHECK(!running_rollback
);
370 memory_pressure_listener_
.reset(new base::MemoryPressureListener(base::Bind(
371 &ProfileSyncService::OnMemoryPressure
, weak_factory_
.GetWeakPtr())));
372 startup_controller_
->Reset(GetRegisteredDataTypes());
373 startup_controller_
->TryStart();
376 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
377 DCHECK(!backend_initialized());
378 if (!HasSyncSetupCompleted())
381 // There was a bug where OnUserChoseDatatypes was not properly called on
382 // configuration (see crbug.com/154940). We detect this by checking whether
383 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
384 // completed, it means sync was not properly configured, so we manually
385 // set kSyncKeepEverythingSynced.
386 PrefService
* const pref_service
= profile_
->GetPrefs();
389 if (GetPreferredDataTypes().Size() > 1)
392 const PrefService::Preference
* keep_everything_synced
=
393 pref_service
->FindPreference(
394 sync_driver::prefs::kSyncKeepEverythingSynced
);
395 // This will be false if the preference was properly set or if it's controlled
397 if (!keep_everything_synced
->IsDefaultValue())
400 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
401 // types now, before we configure.
402 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
403 sync_prefs_
.SetKeepEverythingSynced(true);
404 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
407 void ProfileSyncService::StartSyncingWithServer() {
409 backend_
->StartSyncingWithServer();
412 void ProfileSyncService::RegisterAuthNotifications() {
413 oauth2_token_service_
->AddObserver(this);
415 signin()->AddObserver(this);
418 void ProfileSyncService::UnregisterAuthNotifications() {
420 signin()->RemoveObserver(this);
421 oauth2_token_service_
->RemoveObserver(this);
424 void ProfileSyncService::RegisterDataTypeController(
425 DataTypeController
* data_type_controller
) {
427 directory_data_type_controllers_
.count(data_type_controller
->type()),
429 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
430 data_type_controller
->type()));
431 directory_data_type_controllers_
[data_type_controller
->type()] =
432 data_type_controller
;
435 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type
) {
436 DCHECK_EQ(directory_data_type_controllers_
.count(type
), 0U)
437 << "Duplicate registration of type " << ModelTypeToString(type
);
439 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
440 // fixed and we have some way of telling whether or not this type should be
442 non_blocking_data_type_manager_
.RegisterType(type
, false);
445 void ProfileSyncService::InitializeNonBlockingType(
446 syncer::ModelType type
,
447 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
448 const base::WeakPtr
<syncer_v2::ModelTypeSyncProxyImpl
>& type_sync_proxy
) {
449 non_blocking_data_type_manager_
.InitializeType(
450 type
, task_runner
, type_sync_proxy
);
453 bool ProfileSyncService::IsDataTypeControllerRunning(
454 syncer::ModelType type
) const {
455 DataTypeController::TypeMap::const_iterator iter
=
456 directory_data_type_controllers_
.find(type
);
457 if (iter
== directory_data_type_controllers_
.end()) {
460 return iter
->second
->state() == DataTypeController::RUNNING
;
463 sync_driver::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
464 if (!IsDataTypeControllerRunning(syncer::SESSIONS
))
466 return sessions_sync_manager_
.get();
469 browser_sync::FaviconCache
* ProfileSyncService::GetFaviconCache() {
470 return sessions_sync_manager_
->GetFaviconCache();
473 browser_sync::SyncedWindowDelegatesGetter
*
474 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
475 return sessions_sync_manager_
->GetSyncedWindowDelegatesGetter();
478 sync_driver::DeviceInfoTracker
* ProfileSyncService::GetDeviceInfoTracker()
480 return device_info_sync_service_
.get();
483 sync_driver::LocalDeviceInfoProvider
*
484 ProfileSyncService::GetLocalDeviceInfoProvider() {
485 return local_device_
.get();
488 void ProfileSyncService::GetDataTypeControllerStates(
489 DataTypeController::StateMap
* state_map
) const {
490 for (DataTypeController::TypeMap::const_iterator iter
=
491 directory_data_type_controllers_
.begin();
492 iter
!= directory_data_type_controllers_
.end();
494 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
497 SyncCredentials
ProfileSyncService::GetCredentials() {
498 SyncCredentials credentials
;
499 if (backend_mode_
== SYNC
) {
500 credentials
.email
= signin_
->GetEffectiveUsername();
501 DCHECK(!credentials
.email
.empty());
502 credentials
.sync_token
= access_token_
;
504 if (credentials
.sync_token
.empty())
505 credentials
.sync_token
= "credentials_lost";
507 credentials
.scope_set
.insert(signin_
->GetSyncScopeToUse());
513 bool ProfileSyncService::ShouldDeleteSyncFolder() {
514 switch (backend_mode_
) {
516 return !HasSyncSetupCompleted();
528 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
534 SyncCredentials credentials
= GetCredentials();
536 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
537 profile_
->GetRequestContext());
539 if (backend_mode_
== SYNC
&& delete_stale_data
)
542 backend_
->Initialize(this, sync_thread_
.Pass(), GetJsEventHandler(),
544 local_device_
->GetSyncUserAgent(),
545 credentials
, delete_stale_data
,
546 scoped_ptr
<syncer::SyncManagerFactory
>(
547 new syncer::SyncManagerFactory(GetManagerType()))
549 MakeWeakHandle(weak_factory_
.GetWeakPtr()),
550 base::Bind(browser_sync::ChromeReportUnrecoverableError
),
551 network_resources_
.get(), saved_nigori_state_
.Pass());
554 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
555 if (encryption_pending())
557 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
558 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
559 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
560 return !Intersection(preferred_types
, encrypted_types
).Empty();
563 void ProfileSyncService::OnProtocolEvent(
564 const syncer::ProtocolEvent
& event
) {
565 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver
,
566 protocol_event_observers_
,
567 OnProtocolEvent(event
));
570 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
571 syncer::ModelType type
,
572 const syncer::CommitCounters
& counters
) {
573 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
574 type_debug_info_observers_
,
575 OnCommitCountersUpdated(type
, counters
));
578 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
579 syncer::ModelType type
,
580 const syncer::UpdateCounters
& counters
) {
581 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
582 type_debug_info_observers_
,
583 OnUpdateCountersUpdated(type
, counters
));
586 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
587 syncer::ModelType type
,
588 const syncer::StatusCounters
& counters
) {
589 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
590 type_debug_info_observers_
,
591 OnStatusCountersUpdated(type
, counters
));
594 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
595 syncer::ModelType type
) {
596 DCHECK(syncer::UserTypes().Has(type
));
598 if (!GetPreferredDataTypes().Has(type
)) {
599 // We can get here as datatype SyncableServices are typically wired up
600 // to the native datatype even if sync isn't enabled.
601 DVLOG(1) << "Dropping sync startup request because type "
602 << syncer::ModelTypeToString(type
) << "not enabled.";
606 // If this is a data type change after a major version update, reset the
607 // passphrase prompted state and notify observers.
608 if (IsPassphraseRequired() && passphrase_prompt_triggered_by_version_
) {
609 // The major version has changed and a local syncable change was made.
610 // Reset the passphrase prompt state.
611 passphrase_prompt_triggered_by_version_
= false;
612 sync_prefs_
.SetPassphrasePrompted(false);
616 if (backend_
.get()) {
617 DVLOG(1) << "A data type requested sync startup, but it looks like "
618 "something else beat it to the punch.";
622 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
625 void ProfileSyncService::StartUpSlowBackendComponents(
626 ProfileSyncService::BackendMode mode
) {
627 DCHECK_NE(IDLE
, mode
);
628 if (backend_mode_
== mode
) {
632 // Backend mode transition rules:
633 // * can transit from IDLE to any other non-IDLE mode.
634 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
635 // be explicitly shut down before backup/rollback starts.
636 // * can not transit out of ROLLBACK mode until rollback is finished
637 // (successfully or unsuccessfully).
638 // * can not transit out of BACKUP mode until backup is finished
639 // (successfully or unsuccessfully).
640 // * if backup is needed, can only transit to SYNC if backup is finished,
642 if (backend_mode_
== SYNC
) {
643 LOG(DFATAL
) << "Shouldn't switch from mode SYNC to mode " << mode
;
647 if (backend_mode_
== ROLLBACK
||
648 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
649 // Wait for rollback/backup to finish before start new backend.
653 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
654 if (backend_mode_
!= BACKUP
)
655 backup_rollback_controller_
->StartBackup();
659 DVLOG(1) << "Start backend mode: " << mode
;
663 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
665 ShutdownImpl(syncer::STOP_SYNC
);
668 backend_mode_
= mode
;
670 if (backend_mode_
== BACKUP
)
671 backup_start_time_
= base::Time::Now();
673 if (backend_mode_
== SYNC
&& !backup_start_time_
.is_null()) {
674 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
675 base::Time::Now() - backup_start_time_
);
676 backup_start_time_
= base::Time();
679 if (backend_mode_
== ROLLBACK
)
680 ClearBrowsingDataSinceFirstSync();
681 else if (backend_mode_
== SYNC
)
682 CheckSyncBackupIfNeeded();
684 base::FilePath sync_folder
= backend_mode_
== SYNC
?
685 base::FilePath(kSyncDataFolderName
) :
686 base::FilePath(kSyncBackupDataFolderName
);
688 invalidation::InvalidationService
* invalidator
= NULL
;
689 if (backend_mode_
== SYNC
) {
690 invalidation::ProfileInvalidationProvider
* provider
=
691 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
694 invalidator
= provider
->GetInvalidationService();
697 directory_path_
= profile_
->GetPath().Append(sync_folder
);
700 factory_
->CreateSyncBackendHost(
701 profile_
->GetDebugName(),
704 sync_prefs_
.AsWeakPtr(),
707 // Initialize the backend. Every time we start up a new SyncBackendHost,
708 // we'll want to start from a fresh SyncDB, so delete any old one that might
710 InitializeBackend(ShouldDeleteSyncFolder());
712 UpdateFirstSyncTimePref();
714 ReportPreviousSessionMemoryWarningCount();
717 void ProfileSyncService::OnGetTokenSuccess(
718 const OAuth2TokenService::Request
* request
,
719 const std::string
& access_token
,
720 const base::Time
& expiration_time
) {
721 DCHECK_EQ(access_token_request_
, request
);
722 access_token_request_
.reset();
723 access_token_
= access_token
;
724 token_receive_time_
= base::Time::Now();
725 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
727 if (sync_prefs_
.SyncHasAuthError()) {
728 sync_prefs_
.SetSyncAuthError(false);
729 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
734 if (HasSyncingBackend())
735 backend_
->UpdateCredentials(GetCredentials());
737 startup_controller_
->TryStart();
740 void ProfileSyncService::OnGetTokenFailure(
741 const OAuth2TokenService::Request
* request
,
742 const GoogleServiceAuthError
& error
) {
743 DCHECK_EQ(access_token_request_
, request
);
744 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
745 access_token_request_
.reset();
746 last_get_token_error_
= error
;
747 switch (error
.state()) {
748 case GoogleServiceAuthError::CONNECTION_FAILED
:
749 case GoogleServiceAuthError::REQUEST_CANCELED
:
750 case GoogleServiceAuthError::SERVICE_ERROR
:
751 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
752 // Transient error. Retry after some time.
753 request_access_token_backoff_
.InformOfRequest(false);
754 next_token_request_time_
= base::Time::Now() +
755 request_access_token_backoff_
.GetTimeUntilRelease();
756 request_access_token_retry_timer_
.Start(
758 request_access_token_backoff_
.GetTimeUntilRelease(),
759 base::Bind(&ProfileSyncService::RequestAccessToken
,
760 weak_factory_
.GetWeakPtr()));
764 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
765 if (!sync_prefs_
.SyncHasAuthError()) {
766 sync_prefs_
.SetSyncAuthError(true);
767 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
768 AUTH_ERROR_ENCOUNTERED
,
774 if (error
.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
) {
775 LOG(ERROR
) << "Unexpected persistent error: " << error
.ToString();
777 // Show error to user.
778 UpdateAuthErrorState(error
);
783 void ProfileSyncService::OnRefreshTokenAvailable(
784 const std::string
& account_id
) {
785 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
787 tracked_objects::ScopedTracker
tracking_profile(
788 FROM_HERE_WITH_EXPLICIT_FUNCTION(
789 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
791 if (account_id
== signin_
->GetAccountIdToUse())
792 OnRefreshTokensLoaded();
795 void ProfileSyncService::OnRefreshTokenRevoked(
796 const std::string
& account_id
) {
797 if (!IsOAuthRefreshTokenAvailable()) {
798 access_token_
.clear();
799 // The additional check around IsOAuthRefreshTokenAvailable() above
800 // prevents us sounding the alarm if we actually have a valid token but
801 // a refresh attempt failed for any variety of reasons
802 // (e.g. flaky network). It's possible the token we do have is also
803 // invalid, but in that case we should already have (or can expect) an
804 // auth error sent from the sync backend.
805 UpdateAuthErrorState(
806 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
810 void ProfileSyncService::OnRefreshTokensLoaded() {
811 // This notification gets fired when OAuth2TokenService loads the tokens
813 // Initialize the backend if sync is enabled. If the sync token was
814 // not loaded, GetCredentials() will generate invalid credentials to
815 // cause the backend to generate an auth error (crbug.com/121755).
816 if (HasSyncingBackend()) {
817 RequestAccessToken();
819 startup_controller_
->TryStart();
823 void ProfileSyncService::Shutdown() {
824 UnregisterAuthNotifications();
826 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
827 if (sync_error_controller_
) {
828 // Destroy the SyncErrorController when the service shuts down for good.
829 RemoveObserver(sync_error_controller_
.get());
830 sync_error_controller_
.reset();
834 sync_thread_
->Stop();
837 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
839 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
840 // If the backend is already shut down when a DISABLE_SYNC happens,
841 // the data directory needs to be cleaned up here.
842 sync_thread_
->task_runner()->PostTask(
843 FROM_HERE
, base::Bind(&DeleteSyncDataFolder
, directory_path_
));
848 if (reason
== syncer::ShutdownReason::STOP_SYNC
849 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
850 RemoveClientFromServer();
853 non_blocking_data_type_manager_
.DisconnectSyncBackend();
855 // First, we spin down the backend to stop change processing as soon as
857 base::Time shutdown_start_time
= base::Time::Now();
858 backend_
->StopSyncingForShutdown();
860 // Stop all data type controllers, if needed. Note that until Stop
861 // completes, it is possible in theory to have a ChangeProcessor apply a
862 // change from a native model. In that case, it will get applied to the sync
863 // database (which doesn't get destroyed until we destroy the backend below)
864 // as an unsynced change. That will be persisted, and committed on restart.
865 if (directory_data_type_manager_
) {
866 if (directory_data_type_manager_
->state() != DataTypeManager::STOPPED
) {
867 // When aborting as part of shutdown, we should expect an aborted sync
868 // configure result, else we'll dcheck when we try to read the sync error.
869 expect_sync_configuration_aborted_
= true;
870 directory_data_type_manager_
->Stop();
872 directory_data_type_manager_
.reset();
875 // Shutdown the migrator before the backend to ensure it doesn't pull a null
878 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
880 // Move aside the backend so nobody else tries to use it while we are
882 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
883 if (doomed_backend
) {
884 sync_thread_
= doomed_backend
->Shutdown(reason
);
885 doomed_backend
.reset();
887 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
888 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
890 weak_factory_
.InvalidateWeakPtrs();
892 if (backend_mode_
== SYNC
)
893 startup_controller_
->Reset(GetRegisteredDataTypes());
895 // Don't let backup block sync regardless backup succeeded or not.
896 if (backend_mode_
== BACKUP
)
897 backup_finished_
= true;
899 // Sync could be blocked by rollback/backup. Post task to check whether sync
900 // should start after shutting down rollback/backup backend.
901 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
902 reason
!= syncer::SWITCH_MODE_SYNC
&&
903 reason
!= syncer::BROWSER_SHUTDOWN
) {
904 base::ThreadTaskRunnerHandle::Get()->PostTask(
905 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
906 startup_controller_weak_factory_
.GetWeakPtr()));
909 // Clear various flags.
910 backend_mode_
= IDLE
;
911 expect_sync_configuration_aborted_
= false;
912 is_auth_in_progress_
= false;
913 backend_initialized_
= false;
914 cached_passphrase_
.clear();
915 encryption_pending_
= false;
916 encrypt_everything_
= false;
917 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
918 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
919 request_access_token_retry_timer_
.Stop();
920 // Revert to "no auth error".
921 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
922 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
926 // Mark this as a clean shutdown(without crash).
927 sync_prefs_
.SetCleanShutdown(true);
930 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate
) {
933 // TODO(maxbogue): Investigate whether this logic can/should be moved
934 // into ShutdownImpl or SyncBackendHost itself.
935 if (HasSyncingBackend()) {
936 backend_
->UnregisterInvalidationIds();
938 ShutdownImpl(syncer::STOP_SYNC
);
941 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
942 // PSS clients don't think we're set up while we're shutting down.
943 sync_prefs_
.ClearPreferences();
944 ClearUnrecoverableError();
945 ShutdownImpl(syncer::DISABLE_SYNC
);
950 bool ProfileSyncService::HasSyncSetupCompleted() const {
951 return sync_prefs_
.HasSyncSetupCompleted();
954 void ProfileSyncService::SetSyncSetupCompleted() {
955 sync_prefs_
.SetSyncSetupCompleted();
958 void ProfileSyncService::UpdateLastSyncedTime() {
959 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
962 void ProfileSyncService::NotifyObservers() {
963 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
967 void ProfileSyncService::NotifySyncCycleCompleted() {
968 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
969 OnSyncCycleCompleted());
972 void ProfileSyncService::ClearStaleErrors() {
973 ClearUnrecoverableError();
974 last_actionable_error_
= SyncProtocolError();
975 // Clear the data type errors as well.
976 if (directory_data_type_manager_
.get())
977 directory_data_type_manager_
->ResetDataTypeErrors();
981 void ProfileSyncService::ClearUnrecoverableError() {
982 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
983 unrecoverable_error_message_
.clear();
984 unrecoverable_error_location_
= tracked_objects::Location();
987 // An invariant has been violated. Transition to an error state where we try
988 // to do as little work as possible, to avoid further corruption or crashes.
989 void ProfileSyncService::OnUnrecoverableError(
990 const tracked_objects::Location
& from_here
,
991 const std::string
& message
) {
992 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
993 // interface are assumed to originate within the syncer.
994 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
995 OnUnrecoverableErrorImpl(from_here
, message
, true);
998 void ProfileSyncService::OnUnrecoverableErrorImpl(
999 const tracked_objects::Location
& from_here
,
1000 const std::string
& message
,
1001 bool delete_sync_database
) {
1002 DCHECK(HasUnrecoverableError());
1003 unrecoverable_error_message_
= message
;
1004 unrecoverable_error_location_
= from_here
;
1006 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
1007 unrecoverable_error_reason_
,
1008 ERROR_REASON_LIMIT
);
1009 std::string location
;
1010 from_here
.Write(true, true, &location
);
1012 << "Unrecoverable error detected at " << location
1013 << " -- ProfileSyncService unusable: " << message
;
1015 // Shut all data types down.
1016 base::ThreadTaskRunnerHandle::Get()->PostTask(
1019 &ProfileSyncService::ShutdownImpl
, weak_factory_
.GetWeakPtr(),
1020 delete_sync_database
? syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
1023 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
1024 if (!backend_initialized_
)
1026 directory_data_type_manager_
->ReenableType(type
);
1029 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1030 if (backend_mode_
!= SYNC
)
1033 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1035 if (is_first_time_sync_configure_
) {
1036 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1038 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1041 base::Time on_backend_initialized_time
= base::Time::Now();
1042 base::TimeDelta delta
= on_backend_initialized_time
-
1043 startup_controller_
->start_backend_time();
1044 if (is_first_time_sync_configure_
) {
1045 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1047 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1051 void ProfileSyncService::PostBackendInitialization() {
1052 // Never get here for backup / restore.
1053 DCHECK_EQ(backend_mode_
, SYNC
);
1055 if (last_backup_time_
) {
1056 DCHECK(device_info_sync_service_
);
1057 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1060 if (protocol_event_observers_
.might_have_observers()) {
1061 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1064 non_blocking_data_type_manager_
.ConnectSyncBackend(
1065 backend_
->GetSyncContextProxy());
1067 if (type_debug_info_observers_
.might_have_observers()) {
1068 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1071 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1072 // backend is initialized. We want to call this before notifying observers in
1073 // case this operation affects the "passphrase required" status.
1074 ConsumeCachedPassphraseIfPossible();
1076 // The very first time the backend initializes is effectively the first time
1077 // we can say we successfully "synced". LastSyncedTime will only be null in
1078 // this case, because the pref wasn't restored on StartUp.
1079 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1080 UpdateLastSyncedTime();
1083 if (startup_controller_
->auto_start_enabled() && !FirstSetupInProgress()) {
1084 // Backend is initialized but we're not in sync setup, so this must be an
1085 // autostart - mark our sync setup as completed and we'll start syncing
1087 SetSyncSetupCompleted();
1090 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1091 // data type configuration because observer may flag setup as complete and
1092 // trigger data type configuration.
1093 if (HasSyncSetupCompleted()) {
1094 ConfigureDataTypeManager();
1096 DCHECK(FirstSetupInProgress());
1102 void ProfileSyncService::OnBackendInitialized(
1103 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1104 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1105 debug_info_listener
,
1106 const std::string
& cache_guid
,
1108 UpdateBackendInitUMA(success
);
1111 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1112 // and surface error UI to alert the user sync has stopped.
1113 // Keep the directory around for now so that on restart we will retry
1114 // again and potentially succeed in presence of transient file IO failures
1115 // or permissions issues, etc.
1117 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1118 // Unlike every other UnrecoverableError, it does not delete our sync data.
1119 // This exception made sense at the time it was implemented, but our new
1120 // directory corruption recovery mechanism makes it obsolete. By the time
1121 // we get here, we will have already tried and failed to delete the
1122 // directory. It would be no big deal if we tried to delete it again.
1123 OnInternalUnrecoverableError(FROM_HERE
,
1124 "BackendInitialize failure",
1126 ERROR_REASON_BACKEND_INIT_FAILURE
);
1130 backend_initialized_
= true;
1132 sync_js_controller_
.AttachJsBackend(js_backend
);
1133 debug_info_listener_
= debug_info_listener
;
1135 SigninClient
* signin_client
=
1136 ChromeSigninClientFactory::GetForProfile(profile_
);
1137 DCHECK(signin_client
);
1138 std::string signin_scoped_device_id
=
1139 signin_client
->GetSigninScopedDeviceId();
1141 // Initialize local device info.
1142 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1144 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1145 non_blocking_data_type_manager_
.SetPreferredTypes(GetPreferredDataTypes());
1147 // Give the DataTypeControllers a handle to the now initialized backend
1149 for (DataTypeController::TypeMap::iterator it
=
1150 directory_data_type_controllers_
.begin();
1151 it
!= directory_data_type_controllers_
.end(); ++it
) {
1152 it
->second
->OnUserShareReady(GetUserShare());
1155 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1156 ConfigureDataTypeManager();
1158 PostBackendInitialization();
1161 void ProfileSyncService::OnSyncCycleCompleted() {
1162 UpdateLastSyncedTime();
1163 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1164 // Trigger garbage collection of old sessions now that we've downloaded
1165 // any new session data.
1166 base::ThreadTaskRunnerHandle::Get()->PostTask(
1167 FROM_HERE
, base::Bind(&SessionsSyncManager::DoGarbageCollection
,
1168 base::AsWeakPtr(sessions_sync_manager_
.get())));
1170 DVLOG(2) << "Notifying observers sync cycle completed";
1171 NotifySyncCycleCompleted();
1174 void ProfileSyncService::OnExperimentsChanged(
1175 const syncer::Experiments
& experiments
) {
1176 if (current_experiments_
.Matches(experiments
))
1179 current_experiments_
= experiments
;
1181 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1182 experiments
.gcm_invalidations_enabled
);
1183 profile()->GetPrefs()->SetBoolean(
1184 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1185 experiments
.wallet_sync_enabled
);
1188 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1189 is_auth_in_progress_
= false;
1190 last_auth_error_
= error
;
1197 AuthError
ConnectionStatusToAuthError(
1198 syncer::ConnectionStatus status
) {
1200 case syncer::CONNECTION_OK
:
1201 return AuthError::AuthErrorNone();
1203 case syncer::CONNECTION_AUTH_ERROR
:
1204 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1206 case syncer::CONNECTION_SERVER_ERROR
:
1207 return AuthError(AuthError::CONNECTION_FAILED
);
1211 return AuthError(AuthError::CONNECTION_FAILED
);
1217 void ProfileSyncService::OnConnectionStatusChange(
1218 syncer::ConnectionStatus status
) {
1219 connection_status_update_time_
= base::Time::Now();
1220 connection_status_
= status
;
1221 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1222 // Sync server returned error indicating that access token is invalid. It
1223 // could be either expired or access is revoked. Let's request another
1224 // access token and if access is revoked then request for token will fail
1225 // with corresponding error. If access token is repeatedly reported
1226 // invalid, there may be some issues with server, e.g. authentication
1227 // state is inconsistent on sync and token server. In that case, we
1228 // backoff token requests exponentially to avoid hammering token server
1229 // too much and to avoid getting same token due to token server's caching
1230 // policy. |request_access_token_retry_timer_| is used to backoff request
1231 // triggered by both auth error and failure talking to GAIA server.
1232 // Therefore, we're likely to reach the backoff ceiling more quickly than
1233 // you would expect from looking at the BackoffPolicy if both types of
1234 // errors happen. We shouldn't receive two errors back-to-back without
1235 // attempting a token/sync request in between, thus crank up request delay
1236 // unnecessary. This is because we won't make a sync request if we hit an
1237 // error until GAIA succeeds at sending a new token, and we won't request
1238 // a new token unless sync reports a token failure. But to be safe, don't
1239 // schedule request if this happens.
1240 if (request_access_token_retry_timer_
.IsRunning()) {
1241 // The timer to perform a request later is already running; nothing
1242 // further needs to be done at this point.
1243 } else if (request_access_token_backoff_
.failure_count() == 0) {
1244 // First time request without delay. Currently invalid token is used
1245 // to initialize sync backend and we'll always end up here. We don't
1246 // want to delay initialization.
1247 request_access_token_backoff_
.InformOfRequest(false);
1248 RequestAccessToken();
1250 request_access_token_backoff_
.InformOfRequest(false);
1251 request_access_token_retry_timer_
.Start(
1253 request_access_token_backoff_
.GetTimeUntilRelease(),
1254 base::Bind(&ProfileSyncService::RequestAccessToken
,
1255 weak_factory_
.GetWeakPtr()));
1258 // Reset backoff time after successful connection.
1259 if (status
== syncer::CONNECTION_OK
) {
1260 // Request shouldn't be scheduled at this time. But if it is, it's
1261 // possible that sync flips between OK and auth error states rapidly,
1262 // thus hammers token server. To be safe, only reset backoff delay when
1263 // no scheduled request.
1264 if (request_access_token_retry_timer_
.IsRunning()) {
1267 request_access_token_backoff_
.Reset();
1271 const GoogleServiceAuthError auth_error
=
1272 ConnectionStatusToAuthError(status
);
1273 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1274 UpdateAuthErrorState(auth_error
);
1278 void ProfileSyncService::OnPassphraseRequired(
1279 syncer::PassphraseRequiredReason reason
,
1280 const sync_pb::EncryptedData
& pending_keys
) {
1281 DCHECK(backend_
.get());
1282 DCHECK(backend_
->IsNigoriEnabled());
1284 // TODO(lipalani) : add this check to other locations as well.
1285 if (HasUnrecoverableError()) {
1286 // When unrecoverable error is detected we post a task to shutdown the
1287 // backend. The task might not have executed yet.
1291 DVLOG(1) << "Passphrase required with reason: "
1292 << syncer::PassphraseRequiredReasonToString(reason
);
1293 passphrase_required_reason_
= reason
;
1295 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1296 if (directory_data_type_manager_
) {
1297 // Reconfigure without the encrypted types (excluded implicitly via the
1298 // failed datatypes handler).
1299 directory_data_type_manager_
->Configure(types
,
1300 syncer::CONFIGURE_REASON_CRYPTO
);
1303 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1305 // Notify observers that the passphrase status may have changed.
1309 void ProfileSyncService::OnPassphraseAccepted() {
1310 DVLOG(1) << "Received OnPassphraseAccepted.";
1312 // If the pending keys were resolved via keystore, it's possible we never
1313 // consumed our cached passphrase. Clear it now.
1314 if (!cached_passphrase_
.empty())
1315 cached_passphrase_
.clear();
1317 // Reset passphrase_required_reason_ since we know we no longer require the
1318 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1319 // because that can be called by OnPassphraseRequired() if no encrypted data
1320 // types are enabled, and we don't want to clobber the true passphrase error.
1321 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1323 // Make sure the data types that depend on the passphrase are started at
1325 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1326 if (directory_data_type_manager_
) {
1327 // Re-enable any encrypted types if necessary.
1328 directory_data_type_manager_
->Configure(types
,
1329 syncer::CONFIGURE_REASON_CRYPTO
);
1332 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1337 void ProfileSyncService::OnEncryptedTypesChanged(
1338 syncer::ModelTypeSet encrypted_types
,
1339 bool encrypt_everything
) {
1340 encrypted_types_
= encrypted_types
;
1341 encrypt_everything_
= encrypt_everything
;
1342 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1343 DVLOG(1) << "Encrypted types changed to "
1344 << syncer::ModelTypeSetToString(encrypted_types_
)
1345 << " (encrypt everything is set to "
1346 << (encrypt_everything_
? "true" : "false") << ")";
1347 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1352 void ProfileSyncService::OnEncryptionComplete() {
1353 DVLOG(1) << "Encryption complete";
1354 if (encryption_pending_
&& encrypt_everything_
) {
1355 encryption_pending_
= false;
1356 // This is to nudge the integration tests when encryption is
1362 void ProfileSyncService::OnMigrationNeededForTypes(
1363 syncer::ModelTypeSet types
) {
1364 DCHECK(backend_initialized_
);
1365 DCHECK(directory_data_type_manager_
.get());
1367 // Migrator must be valid, because we don't sync until it is created and this
1368 // callback originates from a sync cycle.
1369 migrator_
->MigrateTypes(types
);
1372 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1373 last_actionable_error_
= error
;
1374 DCHECK_NE(last_actionable_error_
.action
,
1375 syncer::UNKNOWN_ACTION
);
1376 switch (error
.action
) {
1377 case syncer::UPGRADE_CLIENT
:
1378 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1379 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1380 case syncer::STOP_AND_RESTART_SYNC
:
1381 // TODO(lipalani) : if setup in progress we want to display these
1382 // actions in the popup. The current experience might not be optimal for
1383 // the user. We just dismiss the dialog.
1384 if (startup_controller_
->setup_in_progress()) {
1385 RequestStop(CLEAR_DATA
);
1386 expect_sync_configuration_aborted_
= true;
1388 // Trigger an unrecoverable error to stop syncing.
1389 OnInternalUnrecoverableError(FROM_HERE
,
1390 last_actionable_error_
.error_description
,
1392 ERROR_REASON_ACTIONABLE_ERROR
);
1394 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1395 backup_rollback_controller_
->OnRollbackReceived();
1396 // Fall through to shutdown backend and sign user out.
1397 case syncer::DISABLE_SYNC_ON_CLIENT
:
1398 RequestStop(CLEAR_DATA
);
1399 #if !defined(OS_CHROMEOS)
1400 // On desktop Chrome, sign out the user after a dashboard clear.
1401 // Skip sign out on ChromeOS/Android.
1402 if (!startup_controller_
->auto_start_enabled()) {
1403 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1404 signin_metrics::SERVER_FORCED_DISABLE
);
1408 case syncer::ROLLBACK_DONE
:
1409 backup_rollback_controller_
->OnRollbackDone();
1411 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1412 // Sync disabled by domain admin. we should stop syncing until next
1414 sync_disabled_by_admin_
= true;
1415 ShutdownImpl(syncer::DISABLE_SYNC
);
1422 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1423 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1424 !backup_rollback_controller_
->StartRollback())) {
1425 // Clean up backup data for sign-out only or when rollback is disabled.
1427 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1428 // Shut down ROLLBACK backend and delete backup DB.
1429 ShutdownImpl(syncer::DISABLE_SYNC
);
1430 sync_prefs_
.ClearFirstSyncTime();
1434 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1435 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) {
1436 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1437 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1438 switches::kSyncEnableClearDataOnPassphraseEncryption
))
1441 // At this point the user has set a custom passphrase and we
1442 // have received the updated nigori state. Time to cache the nigori state,
1443 // shutdown sync, then restart it and restore the cached nigori state.
1444 ShutdownImpl(syncer::DISABLE_SYNC
);
1445 saved_nigori_state_
.reset(
1446 new syncer::SyncEncryptionHandler::NigoriState(nigori_state
));
1447 // TODO(maniscalco): We should also clear the bootstrap keystore key from the
1448 // pref before restarting sync to ensure we obtain a new, valid one when we
1449 // perform the configuration sync cycle (crbug.com/490836).
1450 startup_controller_
->TryStart();
1453 void ProfileSyncService::OnConfigureDone(
1454 const DataTypeManager::ConfigureResult
& result
) {
1455 configure_status_
= result
.status
;
1456 data_type_status_table_
= result
.data_type_status_table
;
1458 if (backend_mode_
!= SYNC
) {
1459 if (configure_status_
== DataTypeManager::OK
) {
1460 StartSyncingWithServer();
1462 // Backup is done after models are associated.
1463 if (backend_mode_
== BACKUP
)
1464 backup_finished_
= true;
1466 // Asynchronously check whether sync needs to start.
1467 base::ThreadTaskRunnerHandle::Get()->PostTask(
1468 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1469 startup_controller_weak_factory_
.GetWeakPtr()));
1470 } else if (!expect_sync_configuration_aborted_
) {
1471 DVLOG(1) << "Backup/rollback backend failed to configure.";
1472 ShutdownImpl(syncer::STOP_SYNC
);
1478 // We should have cleared our cached passphrase before we get here (in
1479 // OnBackendInitialized()).
1480 DCHECK(cached_passphrase_
.empty());
1482 if (!sync_configure_start_time_
.is_null()) {
1483 if (result
.status
== DataTypeManager::OK
) {
1484 base::Time sync_configure_stop_time
= base::Time::Now();
1485 base::TimeDelta delta
= sync_configure_stop_time
-
1486 sync_configure_start_time_
;
1487 if (is_first_time_sync_configure_
) {
1488 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1490 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1494 sync_configure_start_time_
= base::Time();
1497 // Notify listeners that configuration is done.
1498 content::NotificationService::current()->Notify(
1499 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1500 content::Source
<ProfileSyncService
>(this),
1501 content::NotificationService::NoDetails());
1503 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1504 // The possible status values:
1505 // ABORT - Configuration was aborted. This is not an error, if
1506 // initiated by user.
1507 // OK - Some or all types succeeded.
1508 // Everything else is an UnrecoverableError. So treat it as such.
1510 // First handle the abort case.
1511 if (configure_status_
== DataTypeManager::ABORTED
&&
1512 expect_sync_configuration_aborted_
) {
1513 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1514 expect_sync_configuration_aborted_
= false;
1518 // Handle unrecoverable error.
1519 if (configure_status_
!= DataTypeManager::OK
) {
1520 // Something catastrophic had happened. We should only have one
1521 // error representing it.
1522 syncer::SyncError error
=
1523 data_type_status_table_
.GetUnrecoverableError();
1524 DCHECK(error
.IsSet());
1525 std::string message
=
1526 "Sync configuration failed with status " +
1527 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1529 syncer::ModelTypeSetToString(
1530 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1531 ": " + error
.message();
1532 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1533 OnInternalUnrecoverableError(error
.location(),
1536 ERROR_REASON_CONFIGURATION_FAILURE
);
1540 // We should never get in a state where we have no encrypted datatypes
1541 // enabled, and yet we still think we require a passphrase for decryption.
1542 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1543 !IsEncryptedDatatypeEnabled()));
1545 // This must be done before we start syncing with the server to avoid
1546 // sending unencrypted data up on a first time sync.
1547 if (encryption_pending_
)
1548 backend_
->EnableEncryptEverything();
1551 if (migrator_
.get() &&
1552 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1553 // Migration in progress. Let the migrator know we just finished
1554 // configuring something. It will be up to the migrator to call
1555 // StartSyncingWithServer() if migration is now finished.
1556 migrator_
->OnConfigureDone(result
);
1558 StartSyncingWithServer();
1562 void ProfileSyncService::OnConfigureStart() {
1563 sync_configure_start_time_
= base::Time::Now();
1567 ProfileSyncService::SyncStatusSummary
1568 ProfileSyncService::QuerySyncStatusSummary() {
1569 if (HasUnrecoverableError()) {
1570 return UNRECOVERABLE_ERROR
;
1571 } else if (!backend_
) {
1573 } else if (backend_mode_
== BACKUP
) {
1574 return BACKUP_USER_DATA
;
1575 } else if (backend_mode_
== ROLLBACK
) {
1576 return ROLLBACK_USER_DATA
;
1577 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1578 return SETUP_INCOMPLETE
;
1580 backend_
.get() && HasSyncSetupCompleted() &&
1581 directory_data_type_manager_
.get() &&
1582 directory_data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1583 return DATATYPES_NOT_INITIALIZED
;
1584 } else if (IsSyncActive()) {
1587 return UNKNOWN_ERROR
;
1590 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1591 SyncStatusSummary status
= QuerySyncStatusSummary();
1593 std::string config_status_str
=
1594 configure_status_
!= DataTypeManager::UNKNOWN
?
1595 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1598 case UNRECOVERABLE_ERROR
:
1599 return "Unrecoverable error detected";
1601 return "Syncing not enabled";
1602 case SETUP_INCOMPLETE
:
1603 return "First time sync setup incomplete";
1604 case DATATYPES_NOT_INITIALIZED
:
1605 return "Datatypes not fully initialized";
1607 return "Sync service initialized";
1608 case BACKUP_USER_DATA
:
1609 return "Backing-up user data. Status: " + config_status_str
;
1610 case ROLLBACK_USER_DATA
:
1611 return "Restoring user data. Status: " + config_status_str
;
1613 return "Status unknown: Internal error?";
1617 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1618 return startup_controller_
->GetBackendInitializationStateString();
1621 bool ProfileSyncService::auto_start_enabled() const {
1622 return startup_controller_
->auto_start_enabled();
1625 bool ProfileSyncService::setup_in_progress() const {
1626 return startup_controller_
->setup_in_progress();
1629 bool ProfileSyncService::QueryDetailedSyncStatus(
1630 SyncBackendHost::Status
* result
) {
1631 if (backend_
.get() && backend_initialized_
) {
1632 *result
= backend_
->GetDetailedStatus();
1635 SyncBackendHost::Status status
;
1636 status
.sync_protocol_error
= last_actionable_error_
;
1642 const AuthError
& ProfileSyncService::GetAuthError() const {
1643 return last_auth_error_
;
1646 bool ProfileSyncService::FirstSetupInProgress() const {
1647 return !HasSyncSetupCompleted() && startup_controller_
->setup_in_progress();
1650 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1651 // This method is a no-op if |setup_in_progress_| remains unchanged.
1652 if (startup_controller_
->setup_in_progress() == setup_in_progress
)
1655 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1656 if (!setup_in_progress
&& backend_initialized())
1657 ReconfigureDatatypeManager();
1661 bool ProfileSyncService::IsSyncAllowed() const {
1662 return IsSyncAllowedByFlag() && !IsManaged();
1665 bool ProfileSyncService::IsSyncActive() const {
1666 return backend_initialized_
&& backend_mode_
== SYNC
&&
1667 directory_data_type_manager_
&&
1668 directory_data_type_manager_
->state() != DataTypeManager::STOPPED
;
1671 bool ProfileSyncService::IsSignedIn() const {
1672 // Sync is logged in if there is a non-empty effective account id.
1673 return !signin_
->GetAccountIdToUse().empty();
1676 bool ProfileSyncService::backend_initialized() const {
1677 return backend_initialized_
;
1680 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1681 return backend_mode_
;
1684 bool ProfileSyncService::ConfigurationDone() const {
1685 return directory_data_type_manager_
&&
1686 directory_data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1689 bool ProfileSyncService::waiting_for_auth() const {
1690 return is_auth_in_progress_
;
1693 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1694 return current_experiments_
;
1697 bool ProfileSyncService::HasUnrecoverableError() const {
1698 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1701 bool ProfileSyncService::IsPassphraseRequired() const {
1702 return passphrase_required_reason_
!=
1703 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1706 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1707 // If there is an encrypted datatype enabled and we don't have the proper
1708 // passphrase, we must prompt the user for a passphrase. The only way for the
1709 // user to avoid entering their passphrase is to disable the encrypted types.
1710 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1713 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1714 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1715 if (last_synced_time
.is_null())
1716 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1718 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1720 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1721 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1723 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1724 ui::TimeFormat::LENGTH_SHORT
,
1725 time_since_last_sync
);
1728 void ProfileSyncService::UpdateSelectedTypesHistogram(
1729 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1730 if (!HasSyncSetupCompleted() ||
1731 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1732 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1735 // Only log the data types that are shown in the sync settings ui.
1736 // Note: the order of these types must match the ordering of
1737 // the respective types in ModelType
1738 const sync_driver::user_selectable_type::UserSelectableSyncType
1739 user_selectable_types
[] = {
1740 sync_driver::user_selectable_type::BOOKMARKS
,
1741 sync_driver::user_selectable_type::PREFERENCES
,
1742 sync_driver::user_selectable_type::PASSWORDS
,
1743 sync_driver::user_selectable_type::AUTOFILL
,
1744 sync_driver::user_selectable_type::THEMES
,
1745 sync_driver::user_selectable_type::TYPED_URLS
,
1746 sync_driver::user_selectable_type::EXTENSIONS
,
1747 sync_driver::user_selectable_type::APPS
,
1748 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1749 sync_driver::user_selectable_type::PROXY_TABS
,
1752 static_assert(36 == syncer::MODEL_TYPE_COUNT
,
1753 "custom config histogram must be updated");
1755 if (!sync_everything
) {
1756 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1758 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1759 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1761 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1763 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1765 const syncer::ModelType type
= it
.Get();
1766 if (chosen_types
.Has(type
) &&
1767 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1768 // Selected type has changed - log it.
1769 UMA_HISTOGRAM_ENUMERATION(
1771 user_selectable_types
[i
],
1772 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1778 #if defined(OS_CHROMEOS)
1779 void ProfileSyncService::RefreshSpareBootstrapToken(
1780 const std::string
& passphrase
) {
1781 sync_driver::SystemEncryptor encryptor
;
1782 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1783 // The first 2 params (hostname and username) doesn't have any effect here.
1784 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1786 std::string bootstrap_token
;
1787 if (!temp_cryptographer
.AddKey(key_params
)) {
1788 NOTREACHED() << "Failed to add key to cryptographer.";
1790 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1791 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1795 void ProfileSyncService::OnUserChoseDatatypes(
1796 bool sync_everything
,
1797 syncer::ModelTypeSet chosen_types
) {
1798 if (!backend_
.get() && !HasUnrecoverableError()) {
1803 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1804 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1806 if (directory_data_type_manager_
.get())
1807 directory_data_type_manager_
->ResetDataTypeErrors();
1808 ChangePreferredDataTypes(chosen_types
);
1811 void ProfileSyncService::ChangePreferredDataTypes(
1812 syncer::ModelTypeSet preferred_types
) {
1814 DVLOG(1) << "ChangePreferredDataTypes invoked";
1815 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1816 // Will only enable those types that are registered and preferred.
1817 sync_prefs_
.SetPreferredDataTypes(registered_types
, preferred_types
);
1819 // Now reconfigure the DTM.
1820 ReconfigureDatatypeManager();
1822 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1823 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1824 // which types should be enabled and when.
1827 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1828 if (!IsSyncActive() || !ConfigurationDone())
1829 return syncer::ModelTypeSet();
1830 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1831 const syncer::ModelTypeSet failed_types
=
1832 data_type_status_table_
.GetFailedTypes();
1833 return Difference(preferred_types
, failed_types
);
1836 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1837 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1838 const syncer::ModelTypeSet preferred_types
=
1839 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1840 const syncer::ModelTypeSet enforced_types
=
1841 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1842 return Union(preferred_types
, enforced_types
);
1845 syncer::ModelTypeSet
1846 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1847 const syncer::ModelTypeSet registered_directory_types
=
1848 GetRegisteredDirectoryDataTypes();
1849 const syncer::ModelTypeSet preferred_types
=
1850 sync_prefs_
.GetPreferredDataTypes(registered_directory_types
);
1851 const syncer::ModelTypeSet enforced_types
=
1852 Intersection(GetDataTypesFromPreferenceProviders(),
1853 registered_directory_types
);
1854 return Union(preferred_types
, enforced_types
);
1857 syncer::ModelTypeSet
1858 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1859 return sync_prefs_
.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1862 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1863 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1864 // we'll need another way to distinguish user-choosable types from
1865 // programmatically-enabled types.
1866 return GetDataTypesFromPreferenceProviders();
1869 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1870 return Union(GetRegisteredDirectoryDataTypes(),
1871 GetRegisteredNonBlockingDataTypes());
1874 syncer::ModelTypeSet
1875 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1876 syncer::ModelTypeSet registered_types
;
1877 // The directory_data_type_controllers_ are determined by command-line flags;
1878 // that's effectively what controls the values returned here.
1879 for (DataTypeController::TypeMap::const_iterator it
=
1880 directory_data_type_controllers_
.begin();
1881 it
!= directory_data_type_controllers_
.end(); ++it
) {
1882 registered_types
.Put(it
->first
);
1884 return registered_types
;
1887 syncer::ModelTypeSet
1888 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1889 return non_blocking_data_type_manager_
.GetRegisteredTypes();
1892 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1893 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1894 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1895 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1898 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1899 return backend_
->GetPassphraseType();
1902 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1903 return backend_
->GetExplicitPassphraseTime();
1906 bool ProfileSyncService::IsCryptographerReady(
1907 const syncer::BaseTransaction
* trans
) const {
1908 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1911 void ProfileSyncService::ConfigureDataTypeManager() {
1912 // Don't configure datatypes if the setup UI is still on the screen - this
1913 // is to help multi-screen setting UIs (like iOS) where they don't want to
1914 // start syncing data until the user is done configuring encryption options,
1915 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1916 // SetSetupInProgress(false).
1917 if (backend_mode_
== SYNC
&& startup_controller_
->setup_in_progress())
1920 bool restart
= false;
1921 if (!directory_data_type_manager_
) {
1923 directory_data_type_manager_
.reset(
1924 factory_
->CreateDataTypeManager(debug_info_listener_
,
1925 &directory_data_type_controllers_
,
1930 // We create the migrator at the same time.
1932 new browser_sync::BackendMigrator(
1933 profile_
->GetDebugName(), GetUserShare(),
1934 this, directory_data_type_manager_
.get(),
1935 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1936 base::Unretained(this))));
1939 syncer::ModelTypeSet types
;
1940 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1941 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1942 types
= syncer::BackupTypes();
1943 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1945 types
= GetPreferredDirectoryDataTypes();
1946 if (!HasSyncSetupCompleted()) {
1947 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1948 } else if (restart
) {
1949 // Datatype downloads on restart are generally due to newly supported
1950 // datatypes (although it's also possible we're picking up where a failed
1951 // previous configuration left off).
1952 // TODO(sync): consider detecting configuration recovery and setting
1953 // the reason here appropriately.
1954 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1956 // The user initiated a reconfiguration (either to add or remove types).
1957 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1961 directory_data_type_manager_
->Configure(types
, reason
);
1964 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1965 if (backend_
.get() && backend_initialized_
) {
1966 return backend_
->GetUserShare();
1972 syncer::sessions::SyncSessionSnapshot
1973 ProfileSyncService::GetLastSessionSnapshot() const {
1975 return backend_
->GetLastSessionSnapshot();
1976 return syncer::sessions::SyncSessionSnapshot();
1979 bool ProfileSyncService::HasUnsyncedItems() const {
1980 if (HasSyncingBackend() && backend_initialized_
) {
1981 return backend_
->HasUnsyncedItems();
1987 browser_sync::BackendMigrator
*
1988 ProfileSyncService::GetBackendMigratorForTest() {
1989 return migrator_
.get();
1992 void ProfileSyncService::GetModelSafeRoutingInfo(
1993 syncer::ModelSafeRoutingInfo
* out
) const {
1994 if (backend_
.get() && backend_initialized_
) {
1995 backend_
->GetModelSafeRoutingInfo(out
);
2001 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
2002 scoped_ptr
<base::ListValue
> result(new base::ListValue());
2004 if (!backend_
.get() || !backend_initialized_
) {
2005 return result
.release();
2008 DataTypeStatusTable::TypeErrorMap error_map
=
2009 data_type_status_table_
.GetAllErrors();
2010 ModelTypeSet active_types
;
2011 ModelTypeSet passive_types
;
2012 ModelSafeRoutingInfo routing_info
;
2013 backend_
->GetModelSafeRoutingInfo(&routing_info
);
2014 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
2015 it
!= routing_info
.end(); ++it
) {
2016 if (it
->second
== syncer::GROUP_PASSIVE
) {
2017 passive_types
.Put(it
->first
);
2019 active_types
.Put(it
->first
);
2023 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2024 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2025 ModelTypeSet registered
= GetRegisteredDataTypes();
2026 scoped_ptr
<base::DictionaryValue
> type_status_header(
2027 new base::DictionaryValue());
2029 type_status_header
->SetString("name", "Model Type");
2030 type_status_header
->SetString("status", "header");
2031 type_status_header
->SetString("value", "Group Type");
2032 type_status_header
->SetString("num_entries", "Total Entries");
2033 type_status_header
->SetString("num_live", "Live Entries");
2034 result
->Append(type_status_header
.release());
2036 scoped_ptr
<base::DictionaryValue
> type_status
;
2037 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2038 ModelType type
= it
.Get();
2040 type_status
.reset(new base::DictionaryValue());
2041 type_status
->SetString("name", ModelTypeToString(type
));
2043 if (error_map
.find(type
) != error_map
.end()) {
2044 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2045 DCHECK(error
.IsSet());
2046 switch (error
.GetSeverity()) {
2047 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2048 std::string error_text
= "Error: " + error
.location().ToString() +
2049 ", " + error
.GetMessagePrefix() + error
.message();
2050 type_status
->SetString("status", "error");
2051 type_status
->SetString("value", error_text
);
2054 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2055 type_status
->SetString("status", "disabled");
2056 type_status
->SetString("value", error
.message());
2059 NOTREACHED() << "Unexpected error severity.";
2062 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2063 // Show a proxy type in "ok" state unless it is disabled by user.
2064 DCHECK(!throttled_types
.Has(type
));
2065 type_status
->SetString("status", "ok");
2066 type_status
->SetString("value", "Passive");
2067 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2068 type_status
->SetString("status", "warning");
2069 type_status
->SetString("value", "Passive, Throttled");
2070 } else if (passive_types
.Has(type
)) {
2071 type_status
->SetString("status", "warning");
2072 type_status
->SetString("value", "Passive");
2073 } else if (throttled_types
.Has(type
)) {
2074 type_status
->SetString("status", "warning");
2075 type_status
->SetString("value", "Throttled");
2076 } else if (GetRegisteredNonBlockingDataTypes().Has(type
)) {
2077 type_status
->SetString("status", "ok");
2078 type_status
->SetString("value", "Non-Blocking");
2079 } else if (active_types
.Has(type
)) {
2080 type_status
->SetString("status", "ok");
2081 type_status
->SetString("value", "Active: " +
2082 ModelSafeGroupToString(routing_info
[type
]));
2084 type_status
->SetString("status", "warning");
2085 type_status
->SetString("value", "Disabled by User");
2088 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2089 detailed_status
.num_to_delete_entries_by_type
[type
];
2090 type_status
->SetInteger("num_entries",
2091 detailed_status
.num_entries_by_type
[type
]);
2092 type_status
->SetInteger("num_live", live_count
);
2094 result
->Append(type_status
.release());
2096 return result
.release();
2099 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2102 backend_
->DeactivateDataType(type
);
2105 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2106 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2107 // If the backend isn't running yet, OnBackendInitialized() will call this
2108 // method again after the backend starts up.
2109 if (cached_passphrase_
.empty() || !backend_initialized())
2112 // Backend is up and running, so we can consume the cached passphrase.
2113 std::string passphrase
= cached_passphrase_
;
2114 cached_passphrase_
.clear();
2116 // If we need a passphrase to decrypt data, try the cached passphrase.
2117 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2118 if (SetDecryptionPassphrase(passphrase
)) {
2119 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2124 // If we get here, we don't have pending keys (or at least, the passphrase
2125 // doesn't decrypt them) - just try to re-encrypt using the encryption
2127 if (!IsUsingSecondaryPassphrase())
2128 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2131 void ProfileSyncService::RequestAccessToken() {
2132 // Only one active request at a time.
2133 if (access_token_request_
!= NULL
)
2135 request_access_token_retry_timer_
.Stop();
2136 OAuth2TokenService::ScopeSet oauth2_scopes
;
2137 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2139 // Invalidate previous token, otherwise token service will return the same
2141 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2142 if (!access_token_
.empty()) {
2143 oauth2_token_service_
->InvalidateAccessToken(account_id
, oauth2_scopes
,
2147 access_token_
.clear();
2149 token_request_time_
= base::Time::Now();
2150 token_receive_time_
= base::Time();
2151 next_token_request_time_
= base::Time();
2152 access_token_request_
=
2153 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2156 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2157 PassphraseType type
) {
2158 // This should only be called when the backend has been initialized.
2159 DCHECK(backend_initialized());
2160 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2161 "Data is already encrypted using an explicit passphrase";
2162 DCHECK(!(type
== EXPLICIT
&&
2163 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2164 "Can not set explicit passphrase when decryption is needed.";
2166 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2167 << " passphrase for encryption.";
2168 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2169 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2170 // keys. Hence, as long as we're not trying to do an invalid passphrase
2171 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2172 // will succeed. If for some reason a new encryption key arrives via
2173 // sync later, the SBH will trigger another OnPassphraseRequired().
2174 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2177 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2180 bool ProfileSyncService::SetDecryptionPassphrase(
2181 const std::string
& passphrase
) {
2182 if (IsPassphraseRequired()) {
2183 DVLOG(1) << "Setting passphrase for decryption.";
2184 bool result
= backend_
->SetDecryptionPassphrase(passphrase
);
2185 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result
);
2188 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2189 "IsPassphraseRequired() is false.";
2194 bool ProfileSyncService::EncryptEverythingAllowed() const {
2195 return encrypt_everything_allowed_
;
2198 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2199 DCHECK(allowed
|| !backend_initialized() || !EncryptEverythingEnabled());
2200 encrypt_everything_allowed_
= allowed
;
2203 void ProfileSyncService::EnableEncryptEverything() {
2204 DCHECK(EncryptEverythingAllowed());
2206 // Tests override backend_initialized() to always return true, so we
2207 // must check that instead of |backend_initialized_|.
2208 // TODO(akalin): Fix the above. :/
2209 DCHECK(backend_initialized());
2210 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2211 // problems around cancelling encryption in the background (crbug.com/119649).
2212 if (!encrypt_everything_
)
2213 encryption_pending_
= true;
2216 bool ProfileSyncService::encryption_pending() const {
2217 // We may be called during the setup process before we're
2218 // initialized (via IsEncryptedDatatypeEnabled and
2219 // IsPassphraseRequiredForDecryption).
2220 return encryption_pending_
;
2223 bool ProfileSyncService::EncryptEverythingEnabled() const {
2224 DCHECK(backend_initialized_
);
2225 return encrypt_everything_
|| encryption_pending_
;
2228 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2229 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2230 // We may be called during the setup process before we're
2231 // initialized. In this case, we default to the sensitive types.
2232 return encrypted_types_
;
2235 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2236 if (is_sync_managed
) {
2237 StopImpl(CLEAR_DATA
);
2239 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2240 startup_controller_
->TryStart();
2244 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2245 const std::string
& username
,
2246 const std::string
& password
) {
2247 if (IsSyncRequested() && !password
.empty()) {
2248 cached_passphrase_
= password
;
2249 // Try to consume the passphrase we just cached. If the sync backend
2250 // is not running yet, the passphrase will remain cached until the
2251 // backend starts up.
2252 ConsumeCachedPassphraseIfPossible();
2254 #if defined(OS_CHROMEOS)
2255 RefreshSpareBootstrapToken(password
);
2257 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE
) {
2258 // Track the fact that we're still waiting for auth to complete.
2259 is_auth_in_progress_
= true;
2263 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2264 const std::string
& username
) {
2265 sync_disabled_by_admin_
= false;
2266 RequestStop(CLEAR_DATA
);
2268 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2269 need_backup_
= true;
2270 backup_finished_
= false;
2274 void ProfileSyncService::AddObserver(
2275 sync_driver::SyncServiceObserver
* observer
) {
2276 observers_
.AddObserver(observer
);
2279 void ProfileSyncService::RemoveObserver(
2280 sync_driver::SyncServiceObserver
* observer
) {
2281 observers_
.RemoveObserver(observer
);
2284 void ProfileSyncService::AddProtocolEventObserver(
2285 browser_sync::ProtocolEventObserver
* observer
) {
2286 protocol_event_observers_
.AddObserver(observer
);
2287 if (HasSyncingBackend()) {
2288 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2292 void ProfileSyncService::RemoveProtocolEventObserver(
2293 browser_sync::ProtocolEventObserver
* observer
) {
2294 protocol_event_observers_
.RemoveObserver(observer
);
2295 if (HasSyncingBackend() &&
2296 !protocol_event_observers_
.might_have_observers()) {
2297 backend_
->DisableProtocolEventForwarding();
2301 void ProfileSyncService::AddTypeDebugInfoObserver(
2302 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2303 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2304 if (type_debug_info_observers_
.might_have_observers() &&
2305 backend_initialized_
) {
2306 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2310 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2311 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2312 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2313 if (!type_debug_info_observers_
.might_have_observers() &&
2314 backend_initialized_
) {
2315 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2319 void ProfileSyncService::AddPreferenceProvider(
2320 SyncTypePreferenceProvider
* provider
) {
2321 DCHECK(!HasPreferenceProvider(provider
))
2322 << "Providers may only be added once!";
2323 preference_providers_
.insert(provider
);
2326 void ProfileSyncService::RemovePreferenceProvider(
2327 SyncTypePreferenceProvider
* provider
) {
2328 DCHECK(HasPreferenceProvider(provider
))
2329 << "Only providers that have been added before can be removed!";
2330 preference_providers_
.erase(provider
);
2333 bool ProfileSyncService::HasPreferenceProvider(
2334 SyncTypePreferenceProvider
* provider
) const {
2335 return preference_providers_
.count(provider
) > 0;
2340 class GetAllNodesRequestHelper
2341 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2343 GetAllNodesRequestHelper(
2344 syncer::ModelTypeSet requested_types
,
2345 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2347 void OnReceivedNodesForTypes(
2348 const std::vector
<syncer::ModelType
>& types
,
2349 ScopedVector
<base::ListValue
> scoped_node_lists
);
2352 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2353 virtual ~GetAllNodesRequestHelper();
2355 scoped_ptr
<base::ListValue
> result_accumulator_
;
2357 syncer::ModelTypeSet awaiting_types_
;
2358 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2361 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2362 syncer::ModelTypeSet requested_types
,
2363 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2364 : result_accumulator_(new base::ListValue()),
2365 awaiting_types_(requested_types
),
2366 callback_(callback
) {}
2368 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2369 if (!awaiting_types_
.Empty()) {
2371 << "GetAllNodesRequest deleted before request was fulfilled. "
2372 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2376 // Called when the set of nodes for a type or set of types has been returned.
2378 // The nodes for several types can be returned at the same time by specifying
2379 // their types in the |types| array, and putting their results at the
2380 // correspnding indices in the |scoped_node_lists|.
2381 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2382 const std::vector
<syncer::ModelType
>& types
,
2383 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2384 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2386 // Take unsafe ownership of the node list.
2387 std::vector
<base::ListValue
*> node_lists
;
2388 scoped_node_lists
.release(&node_lists
);
2390 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2391 const ModelType type
= types
[i
];
2392 base::ListValue
* node_list
= node_lists
[i
];
2394 // Add these results to our list.
2395 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2396 type_dict
->SetString("type", ModelTypeToString(type
));
2397 type_dict
->Set("nodes", node_list
);
2398 result_accumulator_
->Append(type_dict
.release());
2400 // Remember that this part of the request is satisfied.
2401 awaiting_types_
.Remove(type
);
2404 if (awaiting_types_
.Empty()) {
2405 callback_
.Run(result_accumulator_
.Pass());
2412 void ProfileSyncService::GetAllNodes(
2413 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2414 ModelTypeSet directory_types
= GetRegisteredDirectoryDataTypes();
2415 directory_types
.PutAll(syncer::ControlTypes());
2416 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2417 new GetAllNodesRequestHelper(directory_types
, callback
);
2419 if (!backend_initialized_
) {
2420 // If there's no backend available to fulfill the request, handle it here.
2421 ScopedVector
<base::ListValue
> empty_results
;
2422 std::vector
<ModelType
> type_vector
;
2423 for (ModelTypeSet::Iterator it
= directory_types
.First();
2424 it
.Good(); it
.Inc()) {
2425 type_vector
.push_back(it
.Get());
2426 empty_results
.push_back(new base::ListValue());
2428 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2430 backend_
->GetAllNodesForTypes(
2432 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2436 bool ProfileSyncService::HasObserver(
2437 const sync_driver::SyncServiceObserver
* observer
) const {
2438 return observers_
.HasObserver(observer
);
2441 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2442 return sync_js_controller_
.AsWeakPtr();
2445 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2446 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2450 bool ProfileSyncService::IsSyncAllowedByFlag() {
2451 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2452 switches::kDisableSync
);
2455 bool ProfileSyncService::IsManaged() const {
2456 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2459 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate
) {
2460 sync_prefs_
.SetSyncRequested(false);
2461 StopImpl(data_fate
);
2464 bool ProfileSyncService::IsSyncRequested() const {
2465 return sync_prefs_
.IsSyncRequested();
2468 SigninManagerBase
* ProfileSyncService::signin() const {
2471 return signin_
->GetOriginal();
2474 void ProfileSyncService::RequestStart() {
2476 sync_prefs_
.SetSyncRequested(true);
2477 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2478 startup_controller_
->TryStart();
2481 void ProfileSyncService::ReconfigureDatatypeManager() {
2482 // If we haven't initialized yet, don't configure the DTM as it could cause
2483 // association to start before a Directory has even been created.
2484 if (backend_initialized_
) {
2485 DCHECK(backend_
.get());
2486 ConfigureDataTypeManager();
2487 } else if (HasUnrecoverableError()) {
2488 // There is nothing more to configure. So inform the listeners,
2491 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2492 << "Unrecoverable error.";
2494 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2499 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2501 syncer::ModelTypeSet types
;
2502 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2503 preference_providers_
.begin();
2504 it
!= preference_providers_
.end();
2506 types
.PutAll((*it
)->GetPreferredDataTypes());
2511 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2513 return data_type_status_table_
;
2516 void ProfileSyncService::OnInternalUnrecoverableError(
2517 const tracked_objects::Location
& from_here
,
2518 const std::string
& message
,
2519 bool delete_sync_database
,
2520 UnrecoverableErrorReason reason
) {
2521 DCHECK(!HasUnrecoverableError());
2522 unrecoverable_error_reason_
= reason
;
2523 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2526 syncer::SyncManagerFactory::MANAGER_TYPE
2527 ProfileSyncService::GetManagerType() const {
2528 switch (backend_mode_
) {
2530 return syncer::SyncManagerFactory::NORMAL
;
2532 return syncer::SyncManagerFactory::BACKUP
;
2534 return syncer::SyncManagerFactory::ROLLBACK
;
2538 return syncer::SyncManagerFactory::NORMAL
;
2541 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2542 return request_access_token_retry_timer_
.IsRunning();
2545 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2546 return access_token_
;
2549 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2550 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2553 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2554 return sessions_sync_manager_
.get();
2557 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2558 return device_info_sync_service_
.get();
2561 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2562 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED
),
2563 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2564 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2566 ProfileSyncService::SyncTokenStatus
2567 ProfileSyncService::GetSyncTokenStatus() const {
2568 SyncTokenStatus status
;
2569 status
.connection_status_update_time
= connection_status_update_time_
;
2570 status
.connection_status
= connection_status_
;
2571 status
.token_request_time
= token_request_time_
;
2572 status
.token_receive_time
= token_receive_time_
;
2573 status
.last_get_token_error
= last_get_token_error_
;
2574 if (request_access_token_retry_timer_
.IsRunning())
2575 status
.next_token_request_time
= next_token_request_time_
;
2579 void ProfileSyncService::OverrideNetworkResourcesForTest(
2580 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2581 network_resources_
= network_resources
.Pass();
2584 bool ProfileSyncService::HasSyncingBackend() const {
2585 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2588 void ProfileSyncService::UpdateFirstSyncTimePref() {
2589 if (!IsSignedIn()) {
2590 // Clear if user's not signed in and rollback is done.
2591 if (backend_mode_
!= ROLLBACK
)
2592 sync_prefs_
.ClearFirstSyncTime();
2593 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2594 backend_mode_
== SYNC
) {
2595 // Set if not set before and it's syncing now.
2596 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2600 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2601 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2602 if (first_sync_time
.is_null())
2605 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2611 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2612 BrowsingDataRemover::Observer
* observer
) {
2613 browsing_data_remover_observer_
= observer
;
2616 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2617 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2621 clear_browsing_data_
= c
;
2624 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2625 DCHECK_EQ(backend_mode_
, SYNC
);
2627 #if defined(ENABLE_PRE_SYNC_BACKUP)
2628 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2629 // Check backup once a day.
2630 if (!last_backup_time_
&&
2631 (last_synced_time
.is_null() ||
2632 base::Time::Now() - last_synced_time
>=
2633 base::TimeDelta::FromDays(1))) {
2634 // If sync thread is set, need to serialize check on sync thread after
2635 // closing backup DB.
2637 sync_thread_
->task_runner()->PostTask(
2639 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2640 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2641 base::ThreadTaskRunnerHandle::Get(),
2642 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2643 weak_factory_
.GetWeakPtr())));
2645 content::BrowserThread::PostTask(
2646 content::BrowserThread::FILE, FROM_HERE
,
2647 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2648 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2649 base::ThreadTaskRunnerHandle::Get(),
2650 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2651 weak_factory_
.GetWeakPtr())));
2657 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2658 last_backup_time_
.reset(new base::Time(backup_time
));
2660 DCHECK(device_info_sync_service_
);
2661 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2664 void ProfileSyncService::TryStartSyncAfterBackup() {
2665 startup_controller_
->Reset(GetRegisteredDataTypes());
2666 startup_controller_
->TryStart();
2669 void ProfileSyncService::CleanUpBackup() {
2670 sync_prefs_
.ClearFirstSyncTime();
2671 profile_
->GetIOTaskRunner()->PostTask(
2673 base::Bind(base::IgnoreResult(base::DeleteFile
),
2674 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2678 bool ProfileSyncService::NeedBackup() const {
2679 return need_backup_
;
2682 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2683 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2686 void ProfileSyncService::FlushDirectory() const {
2687 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2688 // If sync is not initialized yet, we fail silently.
2689 if (backend_initialized_
)
2690 backend_
->FlushDirectory();
2693 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2694 return directory_path_
;
2697 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2699 return sync_thread_
->message_loop();
2700 } else if (backend_
) {
2701 return backend_
->GetSyncLoopForTesting();
2707 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types
) {
2708 if (backend_initialized_
)
2709 backend_
->RefreshTypesForTest(types
);
2712 void ProfileSyncService::RemoveClientFromServer() const {
2713 if (!backend_initialized_
) return;
2714 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2715 std::string birthday
;
2716 syncer::UserShare
* user_share
= GetUserShare();
2717 if (user_share
&& user_share
->directory
.get()) {
2718 birthday
= user_share
->directory
->store_birthday();
2720 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2721 sync_stopped_reporter_
->ReportSyncStopped(
2722 access_token_
, cache_guid
, birthday
);
2726 void ProfileSyncService::OnMemoryPressure(
2727 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
2728 if (memory_pressure_level
==
2729 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
2730 sync_prefs_
.SetMemoryPressureWarningCount(
2731 sync_prefs_
.GetMemoryPressureWarningCount() + 1);
2735 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2736 int warning_received
= sync_prefs_
.GetMemoryPressureWarningCount();
2738 if (-1 != warning_received
) {
2739 // -1 means it is new client.
2740 if (!sync_prefs_
.DidSyncShutdownCleanly()) {
2741 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2744 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2748 sync_prefs_
.SetMemoryPressureWarningCount(0);
2749 // Will set to true during a clean shutdown, so crash or something else will
2750 // remain this as false.
2751 sync_prefs_
.SetCleanShutdown(false);