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/sync_backend_host.h"
44 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
45 #include "chrome/browser/sync/glue/sync_start_util.h"
46 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
47 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
48 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
49 #include "chrome/browser/sync/sync_type_preference_provider.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_list.h"
52 #include "chrome/browser/ui/browser_window.h"
53 #include "chrome/browser/ui/global_error/global_error_service.h"
54 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
55 #include "chrome/browser/ui/sync/browser_synced_window_delegates_getter.h"
56 #include "chrome/common/channel_info.h"
57 #include "chrome/common/chrome_switches.h"
58 #include "chrome/common/pref_names.h"
59 #include "chrome/common/url_constants.h"
60 #include "chrome/grit/generated_resources.h"
61 #include "components/autofill/core/common/autofill_pref_names.h"
62 #include "components/invalidation/impl/profile_invalidation_provider.h"
63 #include "components/invalidation/public/invalidation_service.h"
64 #include "components/password_manager/core/browser/password_store.h"
65 #include "components/pref_registry/pref_registry_syncable.h"
66 #include "components/signin/core/browser/about_signin_internals.h"
67 #include "components/signin/core/browser/profile_oauth2_token_service.h"
68 #include "components/signin/core/browser/signin_manager.h"
69 #include "components/signin/core/browser/signin_metrics.h"
70 #include "components/sync_driver/backend_migrator.h"
71 #include "components/sync_driver/change_processor.h"
72 #include "components/sync_driver/data_type_controller.h"
73 #include "components/sync_driver/device_info.h"
74 #include "components/sync_driver/favicon_cache.h"
75 #include "components/sync_driver/pref_names.h"
76 #include "components/sync_driver/sync_api_component_factory.h"
77 #include "components/sync_driver/sync_driver_switches.h"
78 #include "components/sync_driver/sync_error_controller.h"
79 #include "components/sync_driver/sync_stopped_reporter.h"
80 #include "components/sync_driver/sync_util.h"
81 #include "components/sync_driver/system_encryptor.h"
82 #include "components/sync_driver/user_selectable_sync_type.h"
83 #include "components/version_info/version_info_values.h"
84 #include "content/public/browser/browser_thread.h"
85 #include "content/public/browser/notification_details.h"
86 #include "content/public/browser/notification_service.h"
87 #include "content/public/browser/notification_source.h"
88 #include "net/cookies/cookie_monster.h"
89 #include "net/url_request/url_request_context_getter.h"
90 #include "sync/api/sync_error.h"
91 #include "sync/internal_api/public/configure_reason.h"
92 #include "sync/internal_api/public/http_bridge_network_resources.h"
93 #include "sync/internal_api/public/network_resources.h"
94 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
95 #include "sync/internal_api/public/shutdown_reason.h"
96 #include "sync/internal_api/public/sync_context_proxy.h"
97 #include "sync/internal_api/public/sync_encryption_handler.h"
98 #include "sync/internal_api/public/util/experiments.h"
99 #include "sync/internal_api/public/util/sync_db_util.h"
100 #include "sync/internal_api/public/util/sync_string_conversions.h"
101 #include "sync/js/js_event_details.h"
102 #include "sync/protocol/sync.pb.h"
103 #include "sync/syncable/directory.h"
104 #include "sync/util/cryptographer.h"
105 #include "ui/base/l10n/l10n_util.h"
106 #include "ui/base/l10n/time_format.h"
108 #if defined(OS_ANDROID)
109 #include "chrome/browser/sync/glue/synced_window_delegates_getter_android.h"
110 #include "sync/internal_api/public/read_transaction.h"
113 using browser_sync::NotificationServiceSessionsRouter
;
114 using browser_sync::ProfileSyncServiceStartBehavior
;
115 using browser_sync::SessionsSyncManager
;
116 using browser_sync::SyncBackendHost
;
117 using sync_driver::ChangeProcessor
;
118 using sync_driver::DataTypeController
;
119 using sync_driver::DataTypeManager
;
120 using sync_driver::DataTypeStatusTable
;
121 using sync_driver::DeviceInfoSyncService
;
122 using syncer::ModelType
;
123 using syncer::ModelTypeSet
;
124 using syncer::JsBackend
;
125 using syncer::JsController
;
126 using syncer::JsEventDetails
;
127 using syncer::JsEventHandler
;
128 using syncer::ModelSafeRoutingInfo
;
129 using syncer::SyncCredentials
;
130 using syncer::SyncProtocolError
;
131 using syncer::WeakHandle
;
133 typedef GoogleServiceAuthError AuthError
;
135 const char kSyncUnrecoverableErrorHistogram
[] =
136 "Sync.UnrecoverableErrors";
138 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
139 // Number of initial errors (in sequence) to ignore before applying
140 // exponential back-off rules.
143 // Initial delay for exponential back-off in ms.
146 // Factor by which the waiting time will be multiplied.
149 // Fuzzing percentage. ex: 10% will spread requests randomly
150 // between 90%-100% of the calculated time.
153 // Maximum amount of time we are willing to delay our request in ms.
154 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
155 // RequestAccessToken on connection state change after backoff
156 1000 * 3600 * 4, // 4 hours.
158 // Time to keep an entry from being discarded even when it
159 // has no significant state, -1 to never discard.
162 // Don't use initial delay unless the last request was an error.
166 static const base::FilePath::CharType kSyncDataFolderName
[] =
167 FILE_PATH_LITERAL("Sync Data");
169 static const base::FilePath::CharType kSyncBackupDataFolderName
[] =
170 FILE_PATH_LITERAL("Sync Data Backup");
174 void ClearBrowsingData(BrowsingDataRemover::Observer
* observer
,
178 // BrowsingDataRemover deletes itself when it's done.
179 BrowsingDataRemover
* remover
= BrowsingDataRemover::CreateForRange(
180 profile
, start
, end
);
182 remover
->AddObserver(observer
);
183 remover
->Remove(BrowsingDataRemover::REMOVE_ALL
,
184 BrowsingDataHelper::ALL
);
186 scoped_refptr
<password_manager::PasswordStore
> password
=
187 PasswordStoreFactory::GetForProfile(profile
,
188 ServiceAccessType::EXPLICIT_ACCESS
);
189 password
->RemoveLoginsSyncedBetween(start
, end
);
192 // Perform the actual sync data folder deletion.
193 // This should only be called on the sync thread.
194 void DeleteSyncDataFolder(const base::FilePath
& directory_path
) {
195 if (base::DirectoryExists(directory_path
)) {
196 if (!base::DeleteFile(directory_path
, true))
197 LOG(DFATAL
) << "Could not delete the Sync Data folder.";
201 } // anonymous namespace
203 bool ShouldShowActionOnUI(
204 const syncer::SyncProtocolError
& error
) {
205 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
206 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
207 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
210 ProfileSyncService::ProfileSyncService(
211 scoped_ptr
<sync_driver::SyncApiComponentFactory
> factory
,
213 scoped_ptr
<SigninManagerWrapper
> signin_wrapper
,
214 ProfileOAuth2TokenService
* oauth2_token_service
,
215 ProfileSyncServiceStartBehavior start_behavior
)
216 : OAuth2TokenService::Consumer("sync"),
217 last_auth_error_(AuthError::AuthErrorNone()),
218 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
219 factory_(factory
.Pass()),
221 sync_prefs_(profile_
->GetPrefs()),
223 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
224 chrome::GetChannel())),
225 is_first_time_sync_configure_(false),
226 backend_initialized_(false),
227 sync_disabled_by_admin_(false),
228 is_auth_in_progress_(false),
229 signin_(signin_wrapper
.Pass()),
230 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
231 expect_sync_configuration_aborted_(false),
232 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
233 encrypt_everything_allowed_(true),
234 encrypt_everything_(false),
235 encryption_pending_(false),
236 configure_status_(DataTypeManager::UNKNOWN
),
237 oauth2_token_service_(oauth2_token_service
),
238 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
239 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
240 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
241 network_resources_(new syncer::HttpBridgeNetworkResources
),
244 backup_finished_(false),
245 clear_browsing_data_(base::Bind(&ClearBrowsingData
)),
246 browsing_data_remover_observer_(NULL
),
247 catch_up_configure_in_progress_(false),
248 passphrase_prompt_triggered_by_version_(false),
250 startup_controller_weak_factory_(this) {
251 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
253 startup_controller_
.reset(new browser_sync::StartupController(
255 oauth2_token_service
,
258 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
259 startup_controller_weak_factory_
.GetWeakPtr(),
261 backup_rollback_controller_
.reset(new browser_sync::BackupRollbackController(
264 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
265 startup_controller_weak_factory_
.GetWeakPtr(),
267 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
268 startup_controller_weak_factory_
.GetWeakPtr(),
270 syncer::SyncableService::StartSyncFlare
flare(
271 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
272 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
273 new NotificationServiceSessionsRouter(profile
, flare
));
275 DCHECK(factory_
.get());
276 local_device_
= factory_
->CreateLocalDeviceInfoProvider();
277 sync_stopped_reporter_
.reset(
278 new browser_sync::SyncStoppedReporter(
280 local_device_
->GetSyncUserAgent(),
281 profile_
->GetRequestContext(),
282 browser_sync::SyncStoppedReporter::ResultCallback()));
283 scoped_ptr
<browser_sync::SyncedWindowDelegatesGetter
> synced_window_getter(
284 #if defined(OS_ANDROID)
285 new browser_sync::SyncedWindowDelegatesGetterAndroid());
287 new browser_sync::BrowserSyncedWindowDelegatesGetter());
289 sessions_sync_manager_
.reset(
290 new SessionsSyncManager(profile
, local_device_
.get(), router
.Pass(),
291 synced_window_getter
.Pass()));
292 device_info_sync_service_
.reset(
293 new DeviceInfoSyncService(local_device_
.get()));
295 std::string last_version
= sync_prefs_
.GetLastRunVersion();
296 std::string current_version
= PRODUCT_VERSION
;
297 sync_prefs_
.SetLastRunVersion(current_version
);
299 // Check for a major version change. Note that the versions have format
300 // MAJOR.MINOR.BUILD.PATCH.
301 if (last_version
.substr(0, last_version
.find('.')) !=
302 current_version
.substr(0, current_version
.find('.'))) {
303 passphrase_prompt_triggered_by_version_
= true;
307 ProfileSyncService::~ProfileSyncService() {
308 sync_prefs_
.RemoveSyncPrefObserver(this);
309 // Shutdown() should have been called before destruction.
310 CHECK(!backend_initialized_
);
313 bool ProfileSyncService::CanSyncStart() const {
314 return IsSyncAllowed() && IsSyncRequested() && IsSignedIn();
317 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
318 if (!oauth2_token_service_
)
321 return oauth2_token_service_
->RefreshTokenIsAvailable(
322 signin_
->GetAccountIdToUse());
325 void ProfileSyncService::Initialize() {
326 // We clear this here (vs Shutdown) because we want to remember that an error
327 // happened on shutdown so we can display details (message, location) about it
331 sync_prefs_
.AddSyncPrefObserver(this);
333 // If sync isn't allowed, the only thing to do is to turn it off.
334 if (!IsSyncAllowed()) {
335 RequestStop(CLEAR_DATA
);
339 RegisterAuthNotifications();
341 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
342 // Clean up in case of previous crash / setup abort / signout.
343 StopImpl(CLEAR_DATA
);
346 TrySyncDatatypePrefRecovery();
348 #if defined(OS_CHROMEOS)
349 std::string bootstrap_token
= sync_prefs_
.GetEncryptionBootstrapToken();
350 if (bootstrap_token
.empty()) {
351 sync_prefs_
.SetEncryptionBootstrapToken(
352 sync_prefs_
.GetSpareBootstrapToken());
356 #if !defined(OS_ANDROID)
357 DCHECK(sync_error_controller_
== NULL
)
358 << "Initialize() called more than once.";
359 sync_error_controller_
.reset(new SyncErrorController(this));
360 AddObserver(sync_error_controller_
.get());
363 bool running_rollback
= false;
364 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
365 // Backup is needed if user's not signed in or signed in but previous
366 // backup didn't finish, i.e. backend didn't switch from backup to sync.
367 need_backup_
= !IsSignedIn() || sync_prefs_
.GetFirstSyncTime().is_null();
369 // Try to resume rollback if it didn't finish in last session.
370 running_rollback
= backup_rollback_controller_
->StartRollback();
372 need_backup_
= false;
375 #if defined(ENABLE_PRE_SYNC_BACKUP)
376 if (!running_rollback
&& !IsSignedIn()) {
380 DCHECK(!running_rollback
);
383 memory_pressure_listener_
.reset(new base::MemoryPressureListener(base::Bind(
384 &ProfileSyncService::OnMemoryPressure
, weak_factory_
.GetWeakPtr())));
385 startup_controller_
->Reset(GetRegisteredDataTypes());
386 startup_controller_
->TryStart();
389 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
390 DCHECK(!IsBackendInitialized());
391 if (!HasSyncSetupCompleted())
394 // There was a bug where OnUserChoseDatatypes was not properly called on
395 // configuration (see crbug.com/154940). We detect this by checking whether
396 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
397 // completed, it means sync was not properly configured, so we manually
398 // set kSyncKeepEverythingSynced.
399 PrefService
* const pref_service
= profile_
->GetPrefs();
402 if (GetPreferredDataTypes().Size() > 1)
405 const PrefService::Preference
* keep_everything_synced
=
406 pref_service
->FindPreference(
407 sync_driver::prefs::kSyncKeepEverythingSynced
);
408 // This will be false if the preference was properly set or if it's controlled
410 if (!keep_everything_synced
->IsDefaultValue())
413 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
414 // types now, before we configure.
415 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
416 sync_prefs_
.SetKeepEverythingSynced(true);
417 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
420 void ProfileSyncService::StartSyncingWithServer() {
421 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
423 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
424 switches::kSyncEnableClearDataOnPassphraseEncryption
) &&
425 backend_mode_
== SYNC
&&
426 sync_prefs_
.GetPassphraseEncryptionTransitionInProgress()) {
427 BeginConfigureCatchUpBeforeClear();
432 backend_
->StartSyncingWithServer();
435 void ProfileSyncService::RegisterAuthNotifications() {
436 oauth2_token_service_
->AddObserver(this);
438 signin()->AddObserver(this);
441 void ProfileSyncService::UnregisterAuthNotifications() {
443 signin()->RemoveObserver(this);
444 oauth2_token_service_
->RemoveObserver(this);
447 void ProfileSyncService::RegisterDataTypeController(
448 sync_driver::DataTypeController
* data_type_controller
) {
449 DCHECK_EQ(data_type_controllers_
.count(data_type_controller
->type()), 0U);
450 data_type_controllers_
[data_type_controller
->type()] = data_type_controller
;
453 bool ProfileSyncService::IsDataTypeControllerRunning(
454 syncer::ModelType type
) const {
455 DataTypeController::TypeMap::const_iterator iter
=
456 data_type_controllers_
.find(type
);
457 if (iter
== 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() const {
485 return local_device_
.get();
488 void ProfileSyncService::GetDataTypeControllerStates(
489 DataTypeController::StateMap
* state_map
) const {
490 for (DataTypeController::TypeMap::const_iterator iter
=
491 data_type_controllers_
.begin();
492 iter
!= data_type_controllers_
.end(); ++iter
)
493 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
496 SyncCredentials
ProfileSyncService::GetCredentials() {
497 SyncCredentials credentials
;
498 if (backend_mode_
== SYNC
) {
499 credentials
.email
= signin_
->GetEffectiveUsername();
500 DCHECK(!credentials
.email
.empty());
501 credentials
.sync_token
= access_token_
;
503 if (credentials
.sync_token
.empty())
504 credentials
.sync_token
= "credentials_lost";
506 credentials
.scope_set
.insert(signin_
->GetSyncScopeToUse());
512 bool ProfileSyncService::ShouldDeleteSyncFolder() {
513 switch (backend_mode_
) {
515 return !HasSyncSetupCompleted();
527 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
533 SyncCredentials credentials
= GetCredentials();
535 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
536 profile_
->GetRequestContext());
538 if (backend_mode_
== SYNC
&& delete_stale_data
)
541 backend_
->Initialize(this, sync_thread_
.Pass(), GetJsEventHandler(),
543 local_device_
->GetSyncUserAgent(),
544 credentials
, delete_stale_data
,
545 scoped_ptr
<syncer::SyncManagerFactory
>(
546 new syncer::SyncManagerFactory(GetManagerType()))
548 MakeWeakHandle(weak_factory_
.GetWeakPtr()),
549 base::Bind(browser_sync::ChromeReportUnrecoverableError
),
550 network_resources_
.get(), saved_nigori_state_
.Pass());
553 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
554 if (encryption_pending())
556 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
557 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
558 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
559 return !Intersection(preferred_types
, encrypted_types
).Empty();
562 void ProfileSyncService::OnProtocolEvent(
563 const syncer::ProtocolEvent
& event
) {
564 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver
,
565 protocol_event_observers_
,
566 OnProtocolEvent(event
));
569 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
570 syncer::ModelType type
,
571 const syncer::CommitCounters
& counters
) {
572 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
573 type_debug_info_observers_
,
574 OnCommitCountersUpdated(type
, counters
));
577 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
578 syncer::ModelType type
,
579 const syncer::UpdateCounters
& counters
) {
580 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
581 type_debug_info_observers_
,
582 OnUpdateCountersUpdated(type
, counters
));
585 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
586 syncer::ModelType type
,
587 const syncer::StatusCounters
& counters
) {
588 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
589 type_debug_info_observers_
,
590 OnStatusCountersUpdated(type
, counters
));
593 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
594 syncer::ModelType type
) {
595 DCHECK(syncer::UserTypes().Has(type
));
597 if (!GetPreferredDataTypes().Has(type
)) {
598 // We can get here as datatype SyncableServices are typically wired up
599 // to the native datatype even if sync isn't enabled.
600 DVLOG(1) << "Dropping sync startup request because type "
601 << syncer::ModelTypeToString(type
) << "not enabled.";
605 // If this is a data type change after a major version update, reset the
606 // passphrase prompted state and notify observers.
607 if (IsPassphraseRequired() && passphrase_prompt_triggered_by_version_
) {
608 // The major version has changed and a local syncable change was made.
609 // Reset the passphrase prompt state.
610 passphrase_prompt_triggered_by_version_
= false;
611 sync_prefs_
.SetPassphrasePrompted(false);
615 if (backend_
.get()) {
616 DVLOG(1) << "A data type requested sync startup, but it looks like "
617 "something else beat it to the punch.";
621 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
624 void ProfileSyncService::StartUpSlowBackendComponents(
625 ProfileSyncService::BackendMode mode
) {
626 DCHECK_NE(IDLE
, mode
);
627 if (backend_mode_
== mode
) {
631 // Backend mode transition rules:
632 // * can transit from IDLE to any other non-IDLE mode.
633 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
634 // be explicitly shut down before backup/rollback starts.
635 // * can not transit out of ROLLBACK mode until rollback is finished
636 // (successfully or unsuccessfully).
637 // * can not transit out of BACKUP mode until backup is finished
638 // (successfully or unsuccessfully).
639 // * if backup is needed, can only transit to SYNC if backup is finished,
641 if (backend_mode_
== SYNC
) {
642 LOG(DFATAL
) << "Shouldn't switch from mode SYNC to mode " << mode
;
646 if (backend_mode_
== ROLLBACK
||
647 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
648 // Wait for rollback/backup to finish before start new backend.
652 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
653 if (backend_mode_
!= BACKUP
)
654 backup_rollback_controller_
->StartBackup();
658 DVLOG(1) << "Start backend mode: " << mode
;
662 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
664 ShutdownImpl(syncer::STOP_SYNC
);
667 backend_mode_
= mode
;
669 if (backend_mode_
== BACKUP
)
670 backup_start_time_
= base::Time::Now();
672 if (backend_mode_
== SYNC
&& !backup_start_time_
.is_null()) {
673 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
674 base::Time::Now() - backup_start_time_
);
675 backup_start_time_
= base::Time();
678 if (backend_mode_
== ROLLBACK
)
679 ClearBrowsingDataSinceFirstSync();
680 else if (backend_mode_
== SYNC
)
681 CheckSyncBackupIfNeeded();
683 base::FilePath sync_folder
= backend_mode_
== SYNC
?
684 base::FilePath(kSyncDataFolderName
) :
685 base::FilePath(kSyncBackupDataFolderName
);
687 invalidation::InvalidationService
* invalidator
= NULL
;
688 if (backend_mode_
== SYNC
) {
689 invalidation::ProfileInvalidationProvider
* provider
=
690 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
693 invalidator
= provider
->GetInvalidationService();
696 directory_path_
= profile_
->GetPath().Append(sync_folder
);
699 factory_
->CreateSyncBackendHost(
700 profile_
->GetDebugName(),
702 sync_prefs_
.AsWeakPtr(),
705 // Initialize the backend. Every time we start up a new SyncBackendHost,
706 // we'll want to start from a fresh SyncDB, so delete any old one that might
708 InitializeBackend(ShouldDeleteSyncFolder());
710 UpdateFirstSyncTimePref();
712 ReportPreviousSessionMemoryWarningCount();
715 void ProfileSyncService::OnGetTokenSuccess(
716 const OAuth2TokenService::Request
* request
,
717 const std::string
& access_token
,
718 const base::Time
& expiration_time
) {
719 DCHECK_EQ(access_token_request_
, request
);
720 access_token_request_
.reset();
721 access_token_
= access_token
;
722 token_receive_time_
= base::Time::Now();
723 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
725 if (sync_prefs_
.SyncHasAuthError()) {
726 sync_prefs_
.SetSyncAuthError(false);
727 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
732 if (HasSyncingBackend())
733 backend_
->UpdateCredentials(GetCredentials());
735 startup_controller_
->TryStart();
738 void ProfileSyncService::OnGetTokenFailure(
739 const OAuth2TokenService::Request
* request
,
740 const GoogleServiceAuthError
& error
) {
741 DCHECK_EQ(access_token_request_
, request
);
742 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
743 access_token_request_
.reset();
744 last_get_token_error_
= error
;
745 switch (error
.state()) {
746 case GoogleServiceAuthError::CONNECTION_FAILED
:
747 case GoogleServiceAuthError::REQUEST_CANCELED
:
748 case GoogleServiceAuthError::SERVICE_ERROR
:
749 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
750 // Transient error. Retry after some time.
751 request_access_token_backoff_
.InformOfRequest(false);
752 next_token_request_time_
= base::Time::Now() +
753 request_access_token_backoff_
.GetTimeUntilRelease();
754 request_access_token_retry_timer_
.Start(
756 request_access_token_backoff_
.GetTimeUntilRelease(),
757 base::Bind(&ProfileSyncService::RequestAccessToken
,
758 weak_factory_
.GetWeakPtr()));
762 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
763 if (!sync_prefs_
.SyncHasAuthError()) {
764 sync_prefs_
.SetSyncAuthError(true);
765 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
766 AUTH_ERROR_ENCOUNTERED
,
772 if (error
.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
) {
773 LOG(ERROR
) << "Unexpected persistent error: " << error
.ToString();
775 // Show error to user.
776 UpdateAuthErrorState(error
);
781 void ProfileSyncService::OnRefreshTokenAvailable(
782 const std::string
& account_id
) {
783 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
785 tracked_objects::ScopedTracker
tracking_profile(
786 FROM_HERE_WITH_EXPLICIT_FUNCTION(
787 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
789 if (account_id
== signin_
->GetAccountIdToUse())
790 OnRefreshTokensLoaded();
793 void ProfileSyncService::OnRefreshTokenRevoked(
794 const std::string
& account_id
) {
795 if (!IsOAuthRefreshTokenAvailable()) {
796 access_token_
.clear();
797 // The additional check around IsOAuthRefreshTokenAvailable() above
798 // prevents us sounding the alarm if we actually have a valid token but
799 // a refresh attempt failed for any variety of reasons
800 // (e.g. flaky network). It's possible the token we do have is also
801 // invalid, but in that case we should already have (or can expect) an
802 // auth error sent from the sync backend.
803 UpdateAuthErrorState(
804 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
808 void ProfileSyncService::OnRefreshTokensLoaded() {
809 // This notification gets fired when OAuth2TokenService loads the tokens
811 // Initialize the backend if sync is enabled. If the sync token was
812 // not loaded, GetCredentials() will generate invalid credentials to
813 // cause the backend to generate an auth error (crbug.com/121755).
814 if (HasSyncingBackend()) {
815 RequestAccessToken();
817 startup_controller_
->TryStart();
821 void ProfileSyncService::Shutdown() {
822 UnregisterAuthNotifications();
824 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
825 if (sync_error_controller_
) {
826 // Destroy the SyncErrorController when the service shuts down for good.
827 RemoveObserver(sync_error_controller_
.get());
828 sync_error_controller_
.reset();
832 sync_thread_
->Stop();
835 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
837 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
838 // If the backend is already shut down when a DISABLE_SYNC happens,
839 // the data directory needs to be cleaned up here.
840 sync_thread_
->task_runner()->PostTask(
841 FROM_HERE
, base::Bind(&DeleteSyncDataFolder
, directory_path_
));
846 if (reason
== syncer::ShutdownReason::STOP_SYNC
847 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
848 RemoveClientFromServer();
851 // First, we spin down the backend to stop change processing as soon as
853 base::Time shutdown_start_time
= base::Time::Now();
854 backend_
->StopSyncingForShutdown();
856 // Stop all data type controllers, if needed. Note that until Stop
857 // completes, it is possible in theory to have a ChangeProcessor apply a
858 // change from a native model. In that case, it will get applied to the sync
859 // database (which doesn't get destroyed until we destroy the backend below)
860 // as an unsynced change. That will be persisted, and committed on restart.
861 if (data_type_manager_
) {
862 if (data_type_manager_
->state() != DataTypeManager::STOPPED
) {
863 // When aborting as part of shutdown, we should expect an aborted sync
864 // configure result, else we'll dcheck when we try to read the sync error.
865 expect_sync_configuration_aborted_
= true;
866 data_type_manager_
->Stop();
868 data_type_manager_
.reset();
871 // Shutdown the migrator before the backend to ensure it doesn't pull a null
874 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
876 // Move aside the backend so nobody else tries to use it while we are
878 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
879 if (doomed_backend
) {
880 sync_thread_
= doomed_backend
->Shutdown(reason
);
881 doomed_backend
.reset();
883 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
884 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
886 weak_factory_
.InvalidateWeakPtrs();
888 if (backend_mode_
== SYNC
)
889 startup_controller_
->Reset(GetRegisteredDataTypes());
891 // Don't let backup block sync regardless backup succeeded or not.
892 if (backend_mode_
== BACKUP
)
893 backup_finished_
= true;
895 // Sync could be blocked by rollback/backup. Post task to check whether sync
896 // should start after shutting down rollback/backup backend.
897 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
898 reason
!= syncer::SWITCH_MODE_SYNC
&&
899 reason
!= syncer::BROWSER_SHUTDOWN
) {
900 base::ThreadTaskRunnerHandle::Get()->PostTask(
901 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
902 startup_controller_weak_factory_
.GetWeakPtr()));
905 // Clear various flags.
906 backend_mode_
= IDLE
;
907 expect_sync_configuration_aborted_
= false;
908 is_auth_in_progress_
= false;
909 backend_initialized_
= false;
910 cached_passphrase_
.clear();
911 encryption_pending_
= false;
912 encrypt_everything_
= false;
913 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
914 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
915 catch_up_configure_in_progress_
= false;
916 request_access_token_retry_timer_
.Stop();
917 // Revert to "no auth error".
918 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
919 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
923 // Mark this as a clean shutdown(without crash).
924 sync_prefs_
.SetCleanShutdown(true);
927 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate
) {
930 // TODO(maxbogue): Investigate whether this logic can/should be moved
931 // into ShutdownImpl or SyncBackendHost itself.
932 if (HasSyncingBackend()) {
933 backend_
->UnregisterInvalidationIds();
935 ShutdownImpl(syncer::STOP_SYNC
);
938 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
939 // PSS clients don't think we're set up while we're shutting down.
940 sync_prefs_
.ClearPreferences();
941 ClearUnrecoverableError();
942 ShutdownImpl(syncer::DISABLE_SYNC
);
947 bool ProfileSyncService::HasSyncSetupCompleted() const {
948 return sync_prefs_
.HasSyncSetupCompleted();
951 void ProfileSyncService::SetSyncSetupCompleted() {
952 sync_prefs_
.SetSyncSetupCompleted();
955 void ProfileSyncService::UpdateLastSyncedTime() {
956 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
959 void ProfileSyncService::NotifyObservers() {
960 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
964 void ProfileSyncService::NotifySyncCycleCompleted() {
965 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
966 OnSyncCycleCompleted());
969 void ProfileSyncService::ClearStaleErrors() {
970 ClearUnrecoverableError();
971 last_actionable_error_
= SyncProtocolError();
972 // Clear the data type errors as well.
973 if (data_type_manager_
.get())
974 data_type_manager_
->ResetDataTypeErrors();
977 void ProfileSyncService::ClearUnrecoverableError() {
978 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
979 unrecoverable_error_message_
.clear();
980 unrecoverable_error_location_
= tracked_objects::Location();
983 // An invariant has been violated. Transition to an error state where we try
984 // to do as little work as possible, to avoid further corruption or crashes.
985 void ProfileSyncService::OnUnrecoverableError(
986 const tracked_objects::Location
& from_here
,
987 const std::string
& message
) {
988 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
989 // interface are assumed to originate within the syncer.
990 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
991 OnUnrecoverableErrorImpl(from_here
, message
, true);
994 void ProfileSyncService::OnUnrecoverableErrorImpl(
995 const tracked_objects::Location
& from_here
,
996 const std::string
& message
,
997 bool delete_sync_database
) {
998 DCHECK(HasUnrecoverableError());
999 unrecoverable_error_message_
= message
;
1000 unrecoverable_error_location_
= from_here
;
1002 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
1003 unrecoverable_error_reason_
,
1004 ERROR_REASON_LIMIT
);
1005 std::string location
;
1006 from_here
.Write(true, true, &location
);
1008 << "Unrecoverable error detected at " << location
1009 << " -- ProfileSyncService unusable: " << message
;
1011 // Shut all data types down.
1012 base::ThreadTaskRunnerHandle::Get()->PostTask(
1015 &ProfileSyncService::ShutdownImpl
, weak_factory_
.GetWeakPtr(),
1016 delete_sync_database
? syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
1019 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
1020 if (!backend_initialized_
)
1022 data_type_manager_
->ReenableType(type
);
1025 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1026 if (backend_mode_
!= SYNC
)
1029 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1031 if (is_first_time_sync_configure_
) {
1032 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1034 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1037 base::Time on_backend_initialized_time
= base::Time::Now();
1038 base::TimeDelta delta
= on_backend_initialized_time
-
1039 startup_controller_
->start_backend_time();
1040 if (is_first_time_sync_configure_
) {
1041 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1043 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1047 void ProfileSyncService::PostBackendInitialization() {
1048 // Never get here for backup / restore.
1049 DCHECK_EQ(backend_mode_
, SYNC
);
1051 if (last_backup_time_
) {
1052 DCHECK(device_info_sync_service_
);
1053 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1056 if (protocol_event_observers_
.might_have_observers()) {
1057 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1060 if (type_debug_info_observers_
.might_have_observers()) {
1061 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1064 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1065 // backend is initialized. We want to call this before notifying observers in
1066 // case this operation affects the "passphrase required" status.
1067 ConsumeCachedPassphraseIfPossible();
1069 // The very first time the backend initializes is effectively the first time
1070 // we can say we successfully "synced". LastSyncedTime will only be null in
1071 // this case, because the pref wasn't restored on StartUp.
1072 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1073 UpdateLastSyncedTime();
1076 if (startup_controller_
->auto_start_enabled() && !IsFirstSetupInProgress()) {
1077 // Backend is initialized but we're not in sync setup, so this must be an
1078 // autostart - mark our sync setup as completed and we'll start syncing
1080 SetSyncSetupCompleted();
1083 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1084 // data type configuration because observer may flag setup as complete and
1085 // trigger data type configuration.
1086 if (HasSyncSetupCompleted()) {
1087 ConfigureDataTypeManager();
1089 DCHECK(IsFirstSetupInProgress());
1095 void ProfileSyncService::OnBackendInitialized(
1096 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1097 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1098 debug_info_listener
,
1099 const std::string
& cache_guid
,
1101 UpdateBackendInitUMA(success
);
1104 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1105 // and surface error UI to alert the user sync has stopped.
1106 // Keep the directory around for now so that on restart we will retry
1107 // again and potentially succeed in presence of transient file IO failures
1108 // or permissions issues, etc.
1110 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1111 // Unlike every other UnrecoverableError, it does not delete our sync data.
1112 // This exception made sense at the time it was implemented, but our new
1113 // directory corruption recovery mechanism makes it obsolete. By the time
1114 // we get here, we will have already tried and failed to delete the
1115 // directory. It would be no big deal if we tried to delete it again.
1116 OnInternalUnrecoverableError(FROM_HERE
,
1117 "BackendInitialize failure",
1119 ERROR_REASON_BACKEND_INIT_FAILURE
);
1123 backend_initialized_
= true;
1125 sync_js_controller_
.AttachJsBackend(js_backend
);
1126 debug_info_listener_
= debug_info_listener
;
1128 SigninClient
* signin_client
=
1129 ChromeSigninClientFactory::GetForProfile(profile_
);
1130 DCHECK(signin_client
);
1131 std::string signin_scoped_device_id
=
1132 signin_client
->GetSigninScopedDeviceId();
1134 // Initialize local device info.
1135 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1137 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1138 ConfigureDataTypeManager();
1140 PostBackendInitialization();
1143 void ProfileSyncService::OnSyncCycleCompleted() {
1144 UpdateLastSyncedTime();
1145 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1146 // Trigger garbage collection of old sessions now that we've downloaded
1147 // any new session data.
1148 base::ThreadTaskRunnerHandle::Get()->PostTask(
1149 FROM_HERE
, base::Bind(&SessionsSyncManager::DoGarbageCollection
,
1150 base::AsWeakPtr(sessions_sync_manager_
.get())));
1152 DVLOG(2) << "Notifying observers sync cycle completed";
1153 NotifySyncCycleCompleted();
1156 void ProfileSyncService::OnExperimentsChanged(
1157 const syncer::Experiments
& experiments
) {
1158 if (current_experiments_
.Matches(experiments
))
1161 current_experiments_
= experiments
;
1163 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1164 experiments
.gcm_invalidations_enabled
);
1165 profile()->GetPrefs()->SetBoolean(
1166 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1167 experiments
.wallet_sync_enabled
);
1170 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1171 is_auth_in_progress_
= false;
1172 last_auth_error_
= error
;
1179 AuthError
ConnectionStatusToAuthError(
1180 syncer::ConnectionStatus status
) {
1182 case syncer::CONNECTION_OK
:
1183 return AuthError::AuthErrorNone();
1185 case syncer::CONNECTION_AUTH_ERROR
:
1186 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1188 case syncer::CONNECTION_SERVER_ERROR
:
1189 return AuthError(AuthError::CONNECTION_FAILED
);
1193 return AuthError(AuthError::CONNECTION_FAILED
);
1199 void ProfileSyncService::OnConnectionStatusChange(
1200 syncer::ConnectionStatus status
) {
1201 connection_status_update_time_
= base::Time::Now();
1202 connection_status_
= status
;
1203 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1204 // Sync server returned error indicating that access token is invalid. It
1205 // could be either expired or access is revoked. Let's request another
1206 // access token and if access is revoked then request for token will fail
1207 // with corresponding error. If access token is repeatedly reported
1208 // invalid, there may be some issues with server, e.g. authentication
1209 // state is inconsistent on sync and token server. In that case, we
1210 // backoff token requests exponentially to avoid hammering token server
1211 // too much and to avoid getting same token due to token server's caching
1212 // policy. |request_access_token_retry_timer_| is used to backoff request
1213 // triggered by both auth error and failure talking to GAIA server.
1214 // Therefore, we're likely to reach the backoff ceiling more quickly than
1215 // you would expect from looking at the BackoffPolicy if both types of
1216 // errors happen. We shouldn't receive two errors back-to-back without
1217 // attempting a token/sync request in between, thus crank up request delay
1218 // unnecessary. This is because we won't make a sync request if we hit an
1219 // error until GAIA succeeds at sending a new token, and we won't request
1220 // a new token unless sync reports a token failure. But to be safe, don't
1221 // schedule request if this happens.
1222 if (request_access_token_retry_timer_
.IsRunning()) {
1223 // The timer to perform a request later is already running; nothing
1224 // further needs to be done at this point.
1225 } else if (request_access_token_backoff_
.failure_count() == 0) {
1226 // First time request without delay. Currently invalid token is used
1227 // to initialize sync backend and we'll always end up here. We don't
1228 // want to delay initialization.
1229 request_access_token_backoff_
.InformOfRequest(false);
1230 RequestAccessToken();
1232 request_access_token_backoff_
.InformOfRequest(false);
1233 request_access_token_retry_timer_
.Start(
1235 request_access_token_backoff_
.GetTimeUntilRelease(),
1236 base::Bind(&ProfileSyncService::RequestAccessToken
,
1237 weak_factory_
.GetWeakPtr()));
1240 // Reset backoff time after successful connection.
1241 if (status
== syncer::CONNECTION_OK
) {
1242 // Request shouldn't be scheduled at this time. But if it is, it's
1243 // possible that sync flips between OK and auth error states rapidly,
1244 // thus hammers token server. To be safe, only reset backoff delay when
1245 // no scheduled request.
1246 if (request_access_token_retry_timer_
.IsRunning()) {
1249 request_access_token_backoff_
.Reset();
1253 const GoogleServiceAuthError auth_error
=
1254 ConnectionStatusToAuthError(status
);
1255 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1256 UpdateAuthErrorState(auth_error
);
1260 void ProfileSyncService::OnPassphraseRequired(
1261 syncer::PassphraseRequiredReason reason
,
1262 const sync_pb::EncryptedData
& pending_keys
) {
1263 DCHECK(backend_
.get());
1264 DCHECK(backend_
->IsNigoriEnabled());
1266 // TODO(lipalani) : add this check to other locations as well.
1267 if (HasUnrecoverableError()) {
1268 // When unrecoverable error is detected we post a task to shutdown the
1269 // backend. The task might not have executed yet.
1273 DVLOG(1) << "Passphrase required with reason: "
1274 << syncer::PassphraseRequiredReasonToString(reason
);
1275 passphrase_required_reason_
= reason
;
1277 // TODO(stanisc): http://crbug.com/351005: Does this support USS types?
1278 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1279 if (data_type_manager_
) {
1280 // Reconfigure without the encrypted types (excluded implicitly via the
1281 // failed datatypes handler).
1282 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CRYPTO
);
1285 // Notify observers that the passphrase status may have changed.
1289 void ProfileSyncService::OnPassphraseAccepted() {
1290 DVLOG(1) << "Received OnPassphraseAccepted.";
1292 // If the pending keys were resolved via keystore, it's possible we never
1293 // consumed our cached passphrase. Clear it now.
1294 if (!cached_passphrase_
.empty())
1295 cached_passphrase_
.clear();
1297 // Reset passphrase_required_reason_ since we know we no longer require the
1298 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1299 // because that can be called by OnPassphraseRequired() if no encrypted data
1300 // types are enabled, and we don't want to clobber the true passphrase error.
1301 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1303 // Make sure the data types that depend on the passphrase are started at
1305 // TODO(stanisc): http://crbug.com/351005: Does this support USS types?
1306 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1307 if (data_type_manager_
) {
1308 // Re-enable any encrypted types if necessary.
1309 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CRYPTO
);
1315 void ProfileSyncService::OnEncryptedTypesChanged(
1316 syncer::ModelTypeSet encrypted_types
,
1317 bool encrypt_everything
) {
1318 encrypted_types_
= encrypted_types
;
1319 encrypt_everything_
= encrypt_everything
;
1320 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1321 DVLOG(1) << "Encrypted types changed to "
1322 << syncer::ModelTypeSetToString(encrypted_types_
)
1323 << " (encrypt everything is set to "
1324 << (encrypt_everything_
? "true" : "false") << ")";
1325 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1330 void ProfileSyncService::OnEncryptionComplete() {
1331 DVLOG(1) << "Encryption complete";
1332 if (encryption_pending_
&& encrypt_everything_
) {
1333 encryption_pending_
= false;
1334 // This is to nudge the integration tests when encryption is
1340 void ProfileSyncService::OnMigrationNeededForTypes(
1341 syncer::ModelTypeSet types
) {
1342 DCHECK(backend_initialized_
);
1343 DCHECK(data_type_manager_
.get());
1345 // Migrator must be valid, because we don't sync until it is created and this
1346 // callback originates from a sync cycle.
1347 migrator_
->MigrateTypes(types
);
1350 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1351 last_actionable_error_
= error
;
1352 DCHECK_NE(last_actionable_error_
.action
,
1353 syncer::UNKNOWN_ACTION
);
1354 switch (error
.action
) {
1355 case syncer::UPGRADE_CLIENT
:
1356 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1357 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1358 case syncer::STOP_AND_RESTART_SYNC
:
1359 // TODO(lipalani) : if setup in progress we want to display these
1360 // actions in the popup. The current experience might not be optimal for
1361 // the user. We just dismiss the dialog.
1362 if (startup_controller_
->IsSetupInProgress()) {
1363 RequestStop(CLEAR_DATA
);
1364 expect_sync_configuration_aborted_
= true;
1366 // Trigger an unrecoverable error to stop syncing.
1367 OnInternalUnrecoverableError(FROM_HERE
,
1368 last_actionable_error_
.error_description
,
1370 ERROR_REASON_ACTIONABLE_ERROR
);
1372 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1373 backup_rollback_controller_
->OnRollbackReceived();
1374 // Fall through to shutdown backend and sign user out.
1375 case syncer::DISABLE_SYNC_ON_CLIENT
:
1376 RequestStop(CLEAR_DATA
);
1377 #if !defined(OS_CHROMEOS)
1378 // On desktop Chrome, sign out the user after a dashboard clear.
1379 // Skip sign out on ChromeOS/Android.
1380 if (!startup_controller_
->auto_start_enabled()) {
1381 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1382 signin_metrics::SERVER_FORCED_DISABLE
);
1386 case syncer::ROLLBACK_DONE
:
1387 backup_rollback_controller_
->OnRollbackDone();
1389 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1390 // Sync disabled by domain admin. we should stop syncing until next
1392 sync_disabled_by_admin_
= true;
1393 ShutdownImpl(syncer::DISABLE_SYNC
);
1400 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1401 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1402 !backup_rollback_controller_
->StartRollback())) {
1403 // Clean up backup data for sign-out only or when rollback is disabled.
1405 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1406 // Shut down ROLLBACK backend and delete backup DB.
1407 ShutdownImpl(syncer::DISABLE_SYNC
);
1408 sync_prefs_
.ClearFirstSyncTime();
1412 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1413 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) {
1414 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1415 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1416 switches::kSyncEnableClearDataOnPassphraseEncryption
))
1419 // At this point the user has set a custom passphrase and we have received the
1420 // updated nigori state. Time to cache the nigori state, and catch up the
1421 // active data types.
1422 sync_prefs_
.SetSavedNigoriStateForPassphraseEncryptionTransition(
1424 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(true);
1425 BeginConfigureCatchUpBeforeClear();
1428 void ProfileSyncService::BeginConfigureCatchUpBeforeClear() {
1429 DCHECK_EQ(backend_mode_
, SYNC
);
1430 DCHECK(data_type_manager_
);
1431 DCHECK(!saved_nigori_state_
);
1432 saved_nigori_state_
=
1433 sync_prefs_
.GetSavedNigoriStateForPassphraseEncryptionTransition().Pass();
1434 const syncer::ModelTypeSet types
= GetActiveDataTypes();
1435 catch_up_configure_in_progress_
= true;
1436 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CATCH_UP
);
1439 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() {
1440 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1441 backend_
->ClearServerData(base::Bind(
1442 &ProfileSyncService::OnClearServerDataDone
, weak_factory_
.GetWeakPtr()));
1445 void ProfileSyncService::OnClearServerDataDone() {
1446 DCHECK(sync_prefs_
.GetPassphraseEncryptionTransitionInProgress());
1447 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(false);
1449 // Call to ClearServerData generates new keystore key on the server. This
1450 // makes keystore bootstrap token invalid. Let's clear it from preferences.
1451 sync_prefs_
.SetKeystoreEncryptionBootstrapToken(std::string());
1453 // Shutdown sync, delete the Directory, then restart, restoring the cached
1455 ShutdownImpl(syncer::DISABLE_SYNC
);
1456 startup_controller_
->TryStart();
1459 void ProfileSyncService::OnConfigureDone(
1460 const DataTypeManager::ConfigureResult
& result
) {
1461 configure_status_
= result
.status
;
1462 data_type_status_table_
= result
.data_type_status_table
;
1464 if (backend_mode_
!= SYNC
) {
1465 if (configure_status_
== DataTypeManager::OK
) {
1466 StartSyncingWithServer();
1468 // Backup is done after models are associated.
1469 if (backend_mode_
== BACKUP
)
1470 backup_finished_
= true;
1472 // Asynchronously check whether sync needs to start.
1473 base::ThreadTaskRunnerHandle::Get()->PostTask(
1474 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1475 startup_controller_weak_factory_
.GetWeakPtr()));
1476 } else if (!expect_sync_configuration_aborted_
) {
1477 DVLOG(1) << "Backup/rollback backend failed to configure.";
1478 ShutdownImpl(syncer::STOP_SYNC
);
1484 // We should have cleared our cached passphrase before we get here (in
1485 // OnBackendInitialized()).
1486 DCHECK(cached_passphrase_
.empty());
1488 if (!sync_configure_start_time_
.is_null()) {
1489 if (result
.status
== DataTypeManager::OK
) {
1490 base::Time sync_configure_stop_time
= base::Time::Now();
1491 base::TimeDelta delta
= sync_configure_stop_time
-
1492 sync_configure_start_time_
;
1493 if (is_first_time_sync_configure_
) {
1494 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1496 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1500 sync_configure_start_time_
= base::Time();
1503 // Notify listeners that configuration is done.
1504 content::NotificationService::current()->Notify(
1505 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1506 content::Source
<ProfileSyncService
>(this),
1507 content::NotificationService::NoDetails());
1509 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1510 // The possible status values:
1511 // ABORT - Configuration was aborted. This is not an error, if
1512 // initiated by user.
1513 // OK - Some or all types succeeded.
1514 // Everything else is an UnrecoverableError. So treat it as such.
1516 // First handle the abort case.
1517 if (configure_status_
== DataTypeManager::ABORTED
&&
1518 expect_sync_configuration_aborted_
) {
1519 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1520 expect_sync_configuration_aborted_
= false;
1524 // Handle unrecoverable error.
1525 if (configure_status_
!= DataTypeManager::OK
) {
1526 // Something catastrophic had happened. We should only have one
1527 // error representing it.
1528 syncer::SyncError error
=
1529 data_type_status_table_
.GetUnrecoverableError();
1530 DCHECK(error
.IsSet());
1531 std::string message
=
1532 "Sync configuration failed with status " +
1533 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1535 syncer::ModelTypeSetToString(
1536 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1537 ": " + error
.message();
1538 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1539 OnInternalUnrecoverableError(error
.location(),
1542 ERROR_REASON_CONFIGURATION_FAILURE
);
1546 DCHECK_EQ(DataTypeManager::OK
, configure_status_
);
1548 // We should never get in a state where we have no encrypted datatypes
1549 // enabled, and yet we still think we require a passphrase for decryption.
1550 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1551 !IsEncryptedDatatypeEnabled()));
1553 // This must be done before we start syncing with the server to avoid
1554 // sending unencrypted data up on a first time sync.
1555 if (encryption_pending_
)
1556 backend_
->EnableEncryptEverything();
1559 if (migrator_
.get() &&
1560 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1561 // Migration in progress. Let the migrator know we just finished
1562 // configuring something. It will be up to the migrator to call
1563 // StartSyncingWithServer() if migration is now finished.
1564 migrator_
->OnConfigureDone(result
);
1568 if (catch_up_configure_in_progress_
) {
1569 catch_up_configure_in_progress_
= false;
1570 ClearAndRestartSyncForPassphraseEncryption();
1574 StartSyncingWithServer();
1577 void ProfileSyncService::OnConfigureStart() {
1578 sync_configure_start_time_
= base::Time::Now();
1582 ProfileSyncService::SyncStatusSummary
1583 ProfileSyncService::QuerySyncStatusSummary() {
1584 if (HasUnrecoverableError()) {
1585 return UNRECOVERABLE_ERROR
;
1586 } else if (!backend_
) {
1588 } else if (backend_mode_
== BACKUP
) {
1589 return BACKUP_USER_DATA
;
1590 } else if (backend_mode_
== ROLLBACK
) {
1591 return ROLLBACK_USER_DATA
;
1592 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1593 return SETUP_INCOMPLETE
;
1594 } else if (backend_
&& HasSyncSetupCompleted() && data_type_manager_
&&
1595 data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1596 return DATATYPES_NOT_INITIALIZED
;
1597 } else if (IsSyncActive()) {
1600 return UNKNOWN_ERROR
;
1603 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1604 SyncStatusSummary status
= QuerySyncStatusSummary();
1606 std::string config_status_str
=
1607 configure_status_
!= DataTypeManager::UNKNOWN
?
1608 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1611 case UNRECOVERABLE_ERROR
:
1612 return "Unrecoverable error detected";
1614 return "Syncing not enabled";
1615 case SETUP_INCOMPLETE
:
1616 return "First time sync setup incomplete";
1617 case DATATYPES_NOT_INITIALIZED
:
1618 return "Datatypes not fully initialized";
1620 return "Sync service initialized";
1621 case BACKUP_USER_DATA
:
1622 return "Backing-up user data. Status: " + config_status_str
;
1623 case ROLLBACK_USER_DATA
:
1624 return "Restoring user data. Status: " + config_status_str
;
1626 return "Status unknown: Internal error?";
1630 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1631 return startup_controller_
->GetBackendInitializationStateString();
1634 bool ProfileSyncService::auto_start_enabled() const {
1635 return startup_controller_
->auto_start_enabled();
1638 bool ProfileSyncService::IsSetupInProgress() const {
1639 return startup_controller_
->IsSetupInProgress();
1642 bool ProfileSyncService::QueryDetailedSyncStatus(
1643 SyncBackendHost::Status
* result
) {
1644 if (backend_
.get() && backend_initialized_
) {
1645 *result
= backend_
->GetDetailedStatus();
1648 SyncBackendHost::Status status
;
1649 status
.sync_protocol_error
= last_actionable_error_
;
1655 const AuthError
& ProfileSyncService::GetAuthError() const {
1656 return last_auth_error_
;
1659 bool ProfileSyncService::IsFirstSetupInProgress() const {
1660 return !HasSyncSetupCompleted() && startup_controller_
->IsSetupInProgress();
1663 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1664 // This method is a no-op if |setup_in_progress_| remains unchanged.
1665 if (startup_controller_
->IsSetupInProgress() == setup_in_progress
)
1668 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1669 if (!setup_in_progress
&& IsBackendInitialized())
1670 ReconfigureDatatypeManager();
1674 bool ProfileSyncService::IsSyncAllowed() const {
1675 return IsSyncAllowedByFlag() && !IsManaged();
1678 bool ProfileSyncService::IsSyncActive() const {
1679 return backend_initialized_
&& backend_mode_
== SYNC
&& data_type_manager_
&&
1680 data_type_manager_
->state() != DataTypeManager::STOPPED
;
1683 bool ProfileSyncService::IsSignedIn() const {
1684 // Sync is logged in if there is a non-empty effective account id.
1685 return !signin_
->GetAccountIdToUse().empty();
1688 bool ProfileSyncService::IsBackendInitialized() const {
1689 return backend_initialized_
;
1692 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1693 return backend_mode_
;
1696 bool ProfileSyncService::ConfigurationDone() const {
1697 return data_type_manager_
&&
1698 data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1701 bool ProfileSyncService::waiting_for_auth() const {
1702 return is_auth_in_progress_
;
1705 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1706 return current_experiments_
;
1709 bool ProfileSyncService::HasUnrecoverableError() const {
1710 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1713 bool ProfileSyncService::IsPassphraseRequired() const {
1714 return passphrase_required_reason_
!=
1715 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1718 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1719 // If there is an encrypted datatype enabled and we don't have the proper
1720 // passphrase, we must prompt the user for a passphrase. The only way for the
1721 // user to avoid entering their passphrase is to disable the encrypted types.
1722 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1725 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1726 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1727 if (last_synced_time
.is_null())
1728 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1730 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1732 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1733 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1735 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1736 ui::TimeFormat::LENGTH_SHORT
,
1737 time_since_last_sync
);
1740 void ProfileSyncService::UpdateSelectedTypesHistogram(
1741 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1742 if (!HasSyncSetupCompleted() ||
1743 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1744 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1747 // Only log the data types that are shown in the sync settings ui.
1748 // Note: the order of these types must match the ordering of
1749 // the respective types in ModelType
1750 const sync_driver::user_selectable_type::UserSelectableSyncType
1751 user_selectable_types
[] = {
1752 sync_driver::user_selectable_type::BOOKMARKS
,
1753 sync_driver::user_selectable_type::PREFERENCES
,
1754 sync_driver::user_selectable_type::PASSWORDS
,
1755 sync_driver::user_selectable_type::AUTOFILL
,
1756 sync_driver::user_selectable_type::THEMES
,
1757 sync_driver::user_selectable_type::TYPED_URLS
,
1758 sync_driver::user_selectable_type::EXTENSIONS
,
1759 sync_driver::user_selectable_type::APPS
,
1760 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1761 sync_driver::user_selectable_type::PROXY_TABS
,
1764 static_assert(36 == syncer::MODEL_TYPE_COUNT
,
1765 "custom config histogram must be updated");
1767 if (!sync_everything
) {
1768 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1770 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1771 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1773 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1775 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1777 const syncer::ModelType type
= it
.Get();
1778 if (chosen_types
.Has(type
) &&
1779 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1780 // Selected type has changed - log it.
1781 UMA_HISTOGRAM_ENUMERATION(
1783 user_selectable_types
[i
],
1784 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1790 #if defined(OS_CHROMEOS)
1791 void ProfileSyncService::RefreshSpareBootstrapToken(
1792 const std::string
& passphrase
) {
1793 sync_driver::SystemEncryptor encryptor
;
1794 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1795 // The first 2 params (hostname and username) doesn't have any effect here.
1796 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1798 std::string bootstrap_token
;
1799 if (!temp_cryptographer
.AddKey(key_params
)) {
1800 NOTREACHED() << "Failed to add key to cryptographer.";
1802 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1803 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1807 void ProfileSyncService::OnUserChoseDatatypes(
1808 bool sync_everything
,
1809 syncer::ModelTypeSet chosen_types
) {
1810 if (!backend_
.get() && !HasUnrecoverableError()) {
1815 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1816 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1818 if (data_type_manager_
)
1819 data_type_manager_
->ResetDataTypeErrors();
1820 ChangePreferredDataTypes(chosen_types
);
1823 void ProfileSyncService::ChangePreferredDataTypes(
1824 syncer::ModelTypeSet preferred_types
) {
1826 DVLOG(1) << "ChangePreferredDataTypes invoked";
1827 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1828 // Will only enable those types that are registered and preferred.
1829 sync_prefs_
.SetPreferredDataTypes(registered_types
, preferred_types
);
1831 // Now reconfigure the DTM.
1832 ReconfigureDatatypeManager();
1835 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1836 if (!IsSyncActive() || !ConfigurationDone())
1837 return syncer::ModelTypeSet();
1838 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1839 const syncer::ModelTypeSet failed_types
=
1840 data_type_status_table_
.GetFailedTypes();
1841 return Difference(preferred_types
, failed_types
);
1844 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1845 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1846 const syncer::ModelTypeSet preferred_types
=
1847 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1848 const syncer::ModelTypeSet enforced_types
=
1849 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1850 return Union(preferred_types
, enforced_types
);
1853 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1854 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1855 // we'll need another way to distinguish user-choosable types from
1856 // programmatically-enabled types.
1857 return GetDataTypesFromPreferenceProviders();
1860 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1861 syncer::ModelTypeSet registered_types
;
1862 // The data_type_controllers_ are determined by command-line flags;
1863 // that's effectively what controls the values returned here.
1864 for (DataTypeController::TypeMap::const_iterator it
=
1865 data_type_controllers_
.begin();
1866 it
!= data_type_controllers_
.end(); ++it
) {
1867 registered_types
.Put(it
->first
);
1869 return registered_types
;
1872 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1873 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1874 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1875 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1878 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1879 return backend_
->GetPassphraseType();
1882 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1883 return backend_
->GetExplicitPassphraseTime();
1886 bool ProfileSyncService::IsCryptographerReady(
1887 const syncer::BaseTransaction
* trans
) const {
1888 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1891 void ProfileSyncService::ConfigureDataTypeManager() {
1892 // Don't configure datatypes if the setup UI is still on the screen - this
1893 // is to help multi-screen setting UIs (like iOS) where they don't want to
1894 // start syncing data until the user is done configuring encryption options,
1895 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1896 // SetSetupInProgress(false).
1897 if (backend_mode_
== SYNC
&& startup_controller_
->IsSetupInProgress())
1900 bool restart
= false;
1901 if (!data_type_manager_
) {
1903 data_type_manager_
.reset(factory_
->CreateDataTypeManager(
1904 debug_info_listener_
, &data_type_controllers_
, this, backend_
.get(),
1907 // We create the migrator at the same time.
1908 migrator_
.reset(new browser_sync::BackendMigrator(
1909 profile_
->GetDebugName(), GetUserShare(), this,
1910 data_type_manager_
.get(),
1911 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1912 base::Unretained(this))));
1915 syncer::ModelTypeSet types
;
1916 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1917 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1918 types
= syncer::BackupTypes();
1919 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1921 types
= GetPreferredDataTypes();
1922 if (!HasSyncSetupCompleted()) {
1923 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1924 } else if (restart
) {
1925 // Datatype downloads on restart are generally due to newly supported
1926 // datatypes (although it's also possible we're picking up where a failed
1927 // previous configuration left off).
1928 // TODO(sync): consider detecting configuration recovery and setting
1929 // the reason here appropriately.
1930 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1932 // The user initiated a reconfiguration (either to add or remove types).
1933 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1937 data_type_manager_
->Configure(types
, reason
);
1940 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1941 if (backend_
.get() && backend_initialized_
) {
1942 return backend_
->GetUserShare();
1948 syncer::sessions::SyncSessionSnapshot
1949 ProfileSyncService::GetLastSessionSnapshot() const {
1951 return backend_
->GetLastSessionSnapshot();
1952 return syncer::sessions::SyncSessionSnapshot();
1955 bool ProfileSyncService::HasUnsyncedItems() const {
1956 if (HasSyncingBackend() && backend_initialized_
) {
1957 return backend_
->HasUnsyncedItems();
1963 browser_sync::BackendMigrator
*
1964 ProfileSyncService::GetBackendMigratorForTest() {
1965 return migrator_
.get();
1968 void ProfileSyncService::GetModelSafeRoutingInfo(
1969 syncer::ModelSafeRoutingInfo
* out
) const {
1970 if (backend_
.get() && backend_initialized_
) {
1971 backend_
->GetModelSafeRoutingInfo(out
);
1977 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
1978 scoped_ptr
<base::ListValue
> result(new base::ListValue());
1980 if (!backend_
.get() || !backend_initialized_
) {
1981 return result
.release();
1984 DataTypeStatusTable::TypeErrorMap error_map
=
1985 data_type_status_table_
.GetAllErrors();
1986 ModelTypeSet active_types
;
1987 ModelTypeSet passive_types
;
1988 ModelSafeRoutingInfo routing_info
;
1989 backend_
->GetModelSafeRoutingInfo(&routing_info
);
1990 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
1991 it
!= routing_info
.end(); ++it
) {
1992 if (it
->second
== syncer::GROUP_PASSIVE
) {
1993 passive_types
.Put(it
->first
);
1995 active_types
.Put(it
->first
);
1999 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2000 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2001 ModelTypeSet registered
= GetRegisteredDataTypes();
2002 scoped_ptr
<base::DictionaryValue
> type_status_header(
2003 new base::DictionaryValue());
2005 type_status_header
->SetString("name", "Model Type");
2006 type_status_header
->SetString("status", "header");
2007 type_status_header
->SetString("value", "Group Type");
2008 type_status_header
->SetString("num_entries", "Total Entries");
2009 type_status_header
->SetString("num_live", "Live Entries");
2010 result
->Append(type_status_header
.release());
2012 scoped_ptr
<base::DictionaryValue
> type_status
;
2013 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2014 ModelType type
= it
.Get();
2016 type_status
.reset(new base::DictionaryValue());
2017 type_status
->SetString("name", ModelTypeToString(type
));
2019 if (error_map
.find(type
) != error_map
.end()) {
2020 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2021 DCHECK(error
.IsSet());
2022 switch (error
.GetSeverity()) {
2023 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2024 std::string error_text
= "Error: " + error
.location().ToString() +
2025 ", " + error
.GetMessagePrefix() + error
.message();
2026 type_status
->SetString("status", "error");
2027 type_status
->SetString("value", error_text
);
2030 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2031 type_status
->SetString("status", "disabled");
2032 type_status
->SetString("value", error
.message());
2035 NOTREACHED() << "Unexpected error severity.";
2038 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2039 // Show a proxy type in "ok" state unless it is disabled by user.
2040 DCHECK(!throttled_types
.Has(type
));
2041 type_status
->SetString("status", "ok");
2042 type_status
->SetString("value", "Passive");
2043 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2044 type_status
->SetString("status", "warning");
2045 type_status
->SetString("value", "Passive, Throttled");
2046 } else if (passive_types
.Has(type
)) {
2047 type_status
->SetString("status", "warning");
2048 type_status
->SetString("value", "Passive");
2049 } else if (throttled_types
.Has(type
)) {
2050 type_status
->SetString("status", "warning");
2051 type_status
->SetString("value", "Throttled");
2052 } else if (active_types
.Has(type
)) {
2053 type_status
->SetString("status", "ok");
2054 type_status
->SetString("value", "Active: " +
2055 ModelSafeGroupToString(routing_info
[type
]));
2057 type_status
->SetString("status", "warning");
2058 type_status
->SetString("value", "Disabled by User");
2061 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2062 detailed_status
.num_to_delete_entries_by_type
[type
];
2063 type_status
->SetInteger("num_entries",
2064 detailed_status
.num_entries_by_type
[type
]);
2065 type_status
->SetInteger("num_live", live_count
);
2067 result
->Append(type_status
.release());
2069 return result
.release();
2072 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2075 backend_
->DeactivateDataType(type
);
2078 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2079 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2080 // If the backend isn't running yet, OnBackendInitialized() will call this
2081 // method again after the backend starts up.
2082 if (cached_passphrase_
.empty() || !IsBackendInitialized())
2085 // Backend is up and running, so we can consume the cached passphrase.
2086 std::string passphrase
= cached_passphrase_
;
2087 cached_passphrase_
.clear();
2089 // If we need a passphrase to decrypt data, try the cached passphrase.
2090 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2091 if (SetDecryptionPassphrase(passphrase
)) {
2092 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2097 // If we get here, we don't have pending keys (or at least, the passphrase
2098 // doesn't decrypt them) - just try to re-encrypt using the encryption
2100 if (!IsUsingSecondaryPassphrase())
2101 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2104 void ProfileSyncService::RequestAccessToken() {
2105 // Only one active request at a time.
2106 if (access_token_request_
!= NULL
)
2108 request_access_token_retry_timer_
.Stop();
2109 OAuth2TokenService::ScopeSet oauth2_scopes
;
2110 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2112 // Invalidate previous token, otherwise token service will return the same
2114 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2115 if (!access_token_
.empty()) {
2116 oauth2_token_service_
->InvalidateAccessToken(account_id
, oauth2_scopes
,
2120 access_token_
.clear();
2122 token_request_time_
= base::Time::Now();
2123 token_receive_time_
= base::Time();
2124 next_token_request_time_
= base::Time();
2125 access_token_request_
=
2126 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2129 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2130 PassphraseType type
) {
2131 // This should only be called when the backend has been initialized.
2132 DCHECK(IsBackendInitialized());
2133 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2134 "Data is already encrypted using an explicit passphrase";
2135 DCHECK(!(type
== EXPLICIT
&&
2136 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2137 "Can not set explicit passphrase when decryption is needed.";
2139 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2140 << " passphrase for encryption.";
2141 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2142 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2143 // keys. Hence, as long as we're not trying to do an invalid passphrase
2144 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2145 // will succeed. If for some reason a new encryption key arrives via
2146 // sync later, the SBH will trigger another OnPassphraseRequired().
2147 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2150 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2153 bool ProfileSyncService::SetDecryptionPassphrase(
2154 const std::string
& passphrase
) {
2155 if (IsPassphraseRequired()) {
2156 DVLOG(1) << "Setting passphrase for decryption.";
2157 bool result
= backend_
->SetDecryptionPassphrase(passphrase
);
2158 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result
);
2161 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2162 "IsPassphraseRequired() is false.";
2167 bool ProfileSyncService::IsEncryptEverythingAllowed() const {
2168 return encrypt_everything_allowed_
;
2171 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2172 DCHECK(allowed
|| !IsBackendInitialized() || !IsEncryptEverythingEnabled());
2173 encrypt_everything_allowed_
= allowed
;
2176 void ProfileSyncService::EnableEncryptEverything() {
2177 DCHECK(IsEncryptEverythingAllowed());
2179 // Tests override IsBackendInitialized() to always return true, so we
2180 // must check that instead of |backend_initialized_|.
2181 // TODO(akalin): Fix the above. :/
2182 DCHECK(IsBackendInitialized());
2183 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2184 // problems around cancelling encryption in the background (crbug.com/119649).
2185 if (!encrypt_everything_
)
2186 encryption_pending_
= true;
2189 bool ProfileSyncService::encryption_pending() const {
2190 // We may be called during the setup process before we're
2191 // initialized (via IsEncryptedDatatypeEnabled and
2192 // IsPassphraseRequiredForDecryption).
2193 return encryption_pending_
;
2196 bool ProfileSyncService::IsEncryptEverythingEnabled() const {
2197 DCHECK(backend_initialized_
);
2198 return encrypt_everything_
|| encryption_pending_
;
2201 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2202 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2203 // We may be called during the setup process before we're
2204 // initialized. In this case, we default to the sensitive types.
2205 return encrypted_types_
;
2208 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2209 if (is_sync_managed
) {
2210 StopImpl(CLEAR_DATA
);
2212 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2213 startup_controller_
->TryStart();
2217 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2218 const std::string
& username
,
2219 const std::string
& password
) {
2220 if (IsSyncRequested() && !password
.empty()) {
2221 cached_passphrase_
= password
;
2222 // Try to consume the passphrase we just cached. If the sync backend
2223 // is not running yet, the passphrase will remain cached until the
2224 // backend starts up.
2225 ConsumeCachedPassphraseIfPossible();
2227 #if defined(OS_CHROMEOS)
2228 RefreshSpareBootstrapToken(password
);
2230 if (!IsBackendInitialized() || GetAuthError().state() != AuthError::NONE
) {
2231 // Track the fact that we're still waiting for auth to complete.
2232 is_auth_in_progress_
= true;
2236 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2237 const std::string
& username
) {
2238 sync_disabled_by_admin_
= false;
2239 RequestStop(CLEAR_DATA
);
2241 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2242 need_backup_
= true;
2243 backup_finished_
= false;
2247 void ProfileSyncService::AddObserver(
2248 sync_driver::SyncServiceObserver
* observer
) {
2249 observers_
.AddObserver(observer
);
2252 void ProfileSyncService::RemoveObserver(
2253 sync_driver::SyncServiceObserver
* observer
) {
2254 observers_
.RemoveObserver(observer
);
2257 void ProfileSyncService::AddProtocolEventObserver(
2258 browser_sync::ProtocolEventObserver
* observer
) {
2259 protocol_event_observers_
.AddObserver(observer
);
2260 if (HasSyncingBackend()) {
2261 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2265 void ProfileSyncService::RemoveProtocolEventObserver(
2266 browser_sync::ProtocolEventObserver
* observer
) {
2267 protocol_event_observers_
.RemoveObserver(observer
);
2268 if (HasSyncingBackend() &&
2269 !protocol_event_observers_
.might_have_observers()) {
2270 backend_
->DisableProtocolEventForwarding();
2274 void ProfileSyncService::AddTypeDebugInfoObserver(
2275 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2276 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2277 if (type_debug_info_observers_
.might_have_observers() &&
2278 backend_initialized_
) {
2279 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2283 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2284 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2285 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2286 if (!type_debug_info_observers_
.might_have_observers() &&
2287 backend_initialized_
) {
2288 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2292 void ProfileSyncService::AddPreferenceProvider(
2293 SyncTypePreferenceProvider
* provider
) {
2294 DCHECK(!HasPreferenceProvider(provider
))
2295 << "Providers may only be added once!";
2296 preference_providers_
.insert(provider
);
2299 void ProfileSyncService::RemovePreferenceProvider(
2300 SyncTypePreferenceProvider
* provider
) {
2301 DCHECK(HasPreferenceProvider(provider
))
2302 << "Only providers that have been added before can be removed!";
2303 preference_providers_
.erase(provider
);
2306 bool ProfileSyncService::HasPreferenceProvider(
2307 SyncTypePreferenceProvider
* provider
) const {
2308 return preference_providers_
.count(provider
) > 0;
2313 class GetAllNodesRequestHelper
2314 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2316 GetAllNodesRequestHelper(
2317 syncer::ModelTypeSet requested_types
,
2318 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2320 void OnReceivedNodesForTypes(
2321 const std::vector
<syncer::ModelType
>& types
,
2322 ScopedVector
<base::ListValue
> scoped_node_lists
);
2325 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2326 virtual ~GetAllNodesRequestHelper();
2328 scoped_ptr
<base::ListValue
> result_accumulator_
;
2330 syncer::ModelTypeSet awaiting_types_
;
2331 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2334 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2335 syncer::ModelTypeSet requested_types
,
2336 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2337 : result_accumulator_(new base::ListValue()),
2338 awaiting_types_(requested_types
),
2339 callback_(callback
) {}
2341 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2342 if (!awaiting_types_
.Empty()) {
2344 << "GetAllNodesRequest deleted before request was fulfilled. "
2345 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2349 // Called when the set of nodes for a type or set of types has been returned.
2351 // The nodes for several types can be returned at the same time by specifying
2352 // their types in the |types| array, and putting their results at the
2353 // correspnding indices in the |scoped_node_lists|.
2354 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2355 const std::vector
<syncer::ModelType
>& types
,
2356 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2357 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2359 // Take unsafe ownership of the node list.
2360 std::vector
<base::ListValue
*> node_lists
;
2361 scoped_node_lists
.release(&node_lists
);
2363 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2364 const ModelType type
= types
[i
];
2365 base::ListValue
* node_list
= node_lists
[i
];
2367 // Add these results to our list.
2368 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2369 type_dict
->SetString("type", ModelTypeToString(type
));
2370 type_dict
->Set("nodes", node_list
);
2371 result_accumulator_
->Append(type_dict
.release());
2373 // Remember that this part of the request is satisfied.
2374 awaiting_types_
.Remove(type
);
2377 if (awaiting_types_
.Empty()) {
2378 callback_
.Run(result_accumulator_
.Pass());
2385 void ProfileSyncService::GetAllNodes(
2386 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2387 // TODO(stanisc): crbug.com/328606: Make this work for USS datatypes.
2388 ModelTypeSet all_types
= GetRegisteredDataTypes();
2389 all_types
.PutAll(syncer::ControlTypes());
2390 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2391 new GetAllNodesRequestHelper(all_types
, callback
);
2393 if (!backend_initialized_
) {
2394 // If there's no backend available to fulfill the request, handle it here.
2395 ScopedVector
<base::ListValue
> empty_results
;
2396 std::vector
<ModelType
> type_vector
;
2397 for (ModelTypeSet::Iterator it
= all_types
.First(); it
.Good(); it
.Inc()) {
2398 type_vector
.push_back(it
.Get());
2399 empty_results
.push_back(new base::ListValue());
2401 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2403 backend_
->GetAllNodesForTypes(
2405 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2409 bool ProfileSyncService::HasObserver(
2410 const sync_driver::SyncServiceObserver
* observer
) const {
2411 return observers_
.HasObserver(observer
);
2414 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2415 return sync_js_controller_
.AsWeakPtr();
2418 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2419 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2423 bool ProfileSyncService::IsSyncAllowedByFlag() {
2424 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2425 switches::kDisableSync
);
2428 bool ProfileSyncService::IsManaged() const {
2429 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2432 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate
) {
2433 sync_prefs_
.SetSyncRequested(false);
2434 StopImpl(data_fate
);
2437 bool ProfileSyncService::IsSyncRequested() const {
2438 return sync_prefs_
.IsSyncRequested();
2441 SigninManagerBase
* ProfileSyncService::signin() const {
2444 return signin_
->GetOriginal();
2447 void ProfileSyncService::RequestStart() {
2449 sync_prefs_
.SetSyncRequested(true);
2450 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2451 startup_controller_
->TryStart();
2454 void ProfileSyncService::ReconfigureDatatypeManager() {
2455 // If we haven't initialized yet, don't configure the DTM as it could cause
2456 // association to start before a Directory has even been created.
2457 if (backend_initialized_
) {
2458 DCHECK(backend_
.get());
2459 ConfigureDataTypeManager();
2460 } else if (HasUnrecoverableError()) {
2461 // There is nothing more to configure. So inform the listeners,
2464 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2465 << "Unrecoverable error.";
2467 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2472 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2474 syncer::ModelTypeSet types
;
2475 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2476 preference_providers_
.begin();
2477 it
!= preference_providers_
.end();
2479 types
.PutAll((*it
)->GetPreferredDataTypes());
2484 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2486 return data_type_status_table_
;
2489 void ProfileSyncService::OnInternalUnrecoverableError(
2490 const tracked_objects::Location
& from_here
,
2491 const std::string
& message
,
2492 bool delete_sync_database
,
2493 UnrecoverableErrorReason reason
) {
2494 DCHECK(!HasUnrecoverableError());
2495 unrecoverable_error_reason_
= reason
;
2496 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2499 syncer::SyncManagerFactory::MANAGER_TYPE
2500 ProfileSyncService::GetManagerType() const {
2501 switch (backend_mode_
) {
2503 return syncer::SyncManagerFactory::NORMAL
;
2505 return syncer::SyncManagerFactory::BACKUP
;
2507 return syncer::SyncManagerFactory::ROLLBACK
;
2511 return syncer::SyncManagerFactory::NORMAL
;
2514 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2515 return request_access_token_retry_timer_
.IsRunning();
2518 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2519 return access_token_
;
2522 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2523 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2526 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2527 return sessions_sync_manager_
.get();
2530 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2531 return device_info_sync_service_
.get();
2534 sync_driver::SyncService::SyncTokenStatus
2535 ProfileSyncService::GetSyncTokenStatus() const {
2536 SyncTokenStatus status
;
2537 status
.connection_status_update_time
= connection_status_update_time_
;
2538 status
.connection_status
= connection_status_
;
2539 status
.token_request_time
= token_request_time_
;
2540 status
.token_receive_time
= token_receive_time_
;
2541 status
.last_get_token_error
= last_get_token_error_
;
2542 if (request_access_token_retry_timer_
.IsRunning())
2543 status
.next_token_request_time
= next_token_request_time_
;
2547 void ProfileSyncService::OverrideNetworkResourcesForTest(
2548 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2549 network_resources_
= network_resources
.Pass();
2552 bool ProfileSyncService::HasSyncingBackend() const {
2553 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2556 void ProfileSyncService::UpdateFirstSyncTimePref() {
2557 if (!IsSignedIn()) {
2558 // Clear if user's not signed in and rollback is done.
2559 if (backend_mode_
!= ROLLBACK
)
2560 sync_prefs_
.ClearFirstSyncTime();
2561 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2562 backend_mode_
== SYNC
) {
2563 // Set if not set before and it's syncing now.
2564 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2568 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2569 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2570 if (first_sync_time
.is_null())
2573 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2579 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2580 BrowsingDataRemover::Observer
* observer
) {
2581 browsing_data_remover_observer_
= observer
;
2584 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2585 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2589 clear_browsing_data_
= c
;
2592 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2593 DCHECK_EQ(backend_mode_
, SYNC
);
2595 #if defined(ENABLE_PRE_SYNC_BACKUP)
2596 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2597 // Check backup once a day.
2598 if (!last_backup_time_
&&
2599 (last_synced_time
.is_null() ||
2600 base::Time::Now() - last_synced_time
>=
2601 base::TimeDelta::FromDays(1))) {
2602 // If sync thread is set, need to serialize check on sync thread after
2603 // closing backup DB.
2605 sync_thread_
->task_runner()->PostTask(
2607 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2608 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2609 base::ThreadTaskRunnerHandle::Get(),
2610 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2611 weak_factory_
.GetWeakPtr())));
2613 content::BrowserThread::PostTask(
2614 content::BrowserThread::FILE, FROM_HERE
,
2615 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2616 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2617 base::ThreadTaskRunnerHandle::Get(),
2618 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2619 weak_factory_
.GetWeakPtr())));
2625 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2626 last_backup_time_
.reset(new base::Time(backup_time
));
2628 DCHECK(device_info_sync_service_
);
2629 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2632 void ProfileSyncService::TryStartSyncAfterBackup() {
2633 startup_controller_
->Reset(GetRegisteredDataTypes());
2634 startup_controller_
->TryStart();
2637 void ProfileSyncService::CleanUpBackup() {
2638 sync_prefs_
.ClearFirstSyncTime();
2639 profile_
->GetIOTaskRunner()->PostTask(
2641 base::Bind(base::IgnoreResult(base::DeleteFile
),
2642 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2646 bool ProfileSyncService::NeedBackup() const {
2647 return need_backup_
;
2650 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2651 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2654 void ProfileSyncService::FlushDirectory() const {
2655 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2656 // If sync is not initialized yet, we fail silently.
2657 if (backend_initialized_
)
2658 backend_
->FlushDirectory();
2661 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2662 return directory_path_
;
2665 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2667 return sync_thread_
->message_loop();
2668 } else if (backend_
) {
2669 return backend_
->GetSyncLoopForTesting();
2675 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types
) {
2676 if (backend_initialized_
)
2677 backend_
->RefreshTypesForTest(types
);
2680 void ProfileSyncService::RemoveClientFromServer() const {
2681 if (!backend_initialized_
) return;
2682 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2683 std::string birthday
;
2684 syncer::UserShare
* user_share
= GetUserShare();
2685 if (user_share
&& user_share
->directory
.get()) {
2686 birthday
= user_share
->directory
->store_birthday();
2688 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2689 sync_stopped_reporter_
->ReportSyncStopped(
2690 access_token_
, cache_guid
, birthday
);
2694 void ProfileSyncService::OnMemoryPressure(
2695 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
2696 if (memory_pressure_level
==
2697 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
2698 sync_prefs_
.SetMemoryPressureWarningCount(
2699 sync_prefs_
.GetMemoryPressureWarningCount() + 1);
2703 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2704 int warning_received
= sync_prefs_
.GetMemoryPressureWarningCount();
2706 if (-1 != warning_received
) {
2707 // -1 means it is new client.
2708 if (!sync_prefs_
.DidSyncShutdownCleanly()) {
2709 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2712 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2716 sync_prefs_
.SetMemoryPressureWarningCount(0);
2717 // Will set to true during a clean shutdown, so crash or something else will
2718 // remain this as false.
2719 sync_prefs_
.SetCleanShutdown(false);
2722 const GURL
& ProfileSyncService::sync_service_url() const {
2723 return sync_service_url_
;
2726 std::string
ProfileSyncService::unrecoverable_error_message() const {
2727 return unrecoverable_error_message_
;
2730 tracked_objects::Location
ProfileSyncService::unrecoverable_error_location()
2732 return unrecoverable_error_location_
;