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/profiles/profile.h"
37 #include "chrome/browser/signin/about_signin_internals_factory.h"
38 #include "chrome/browser/signin/chrome_signin_client_factory.h"
39 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
40 #include "chrome/browser/signin/signin_manager_factory.h"
41 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
42 #include "chrome/browser/sync/glue/sync_backend_host.h"
43 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
44 #include "chrome/browser/sync/glue/sync_start_util.h"
45 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
46 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
47 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
48 #include "chrome/browser/sync/sync_type_preference_provider.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_list.h"
51 #include "chrome/browser/ui/browser_window.h"
52 #include "chrome/browser/ui/global_error/global_error_service.h"
53 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
54 #include "chrome/browser/ui/sync/browser_synced_window_delegates_getter.h"
55 #include "chrome/common/channel_info.h"
56 #include "chrome/common/chrome_switches.h"
57 #include "chrome/common/pref_names.h"
58 #include "chrome/common/url_constants.h"
59 #include "chrome/grit/generated_resources.h"
60 #include "components/autofill/core/common/autofill_pref_names.h"
61 #include "components/invalidation/impl/profile_invalidation_provider.h"
62 #include "components/invalidation/public/invalidation_service.h"
63 #include "components/password_manager/core/browser/password_store.h"
64 #include "components/pref_registry/pref_registry_syncable.h"
65 #include "components/signin/core/browser/about_signin_internals.h"
66 #include "components/signin/core/browser/profile_oauth2_token_service.h"
67 #include "components/signin/core/browser/signin_manager.h"
68 #include "components/signin/core/browser/signin_metrics.h"
69 #include "components/sync_driver/backend_migrator.h"
70 #include "components/sync_driver/change_processor.h"
71 #include "components/sync_driver/data_type_controller.h"
72 #include "components/sync_driver/device_info.h"
73 #include "components/sync_driver/favicon_cache.h"
74 #include "components/sync_driver/pref_names.h"
75 #include "components/sync_driver/sync_api_component_factory.h"
76 #include "components/sync_driver/sync_driver_switches.h"
77 #include "components/sync_driver/sync_error_controller.h"
78 #include "components/sync_driver/sync_stopped_reporter.h"
79 #include "components/sync_driver/sync_util.h"
80 #include "components/sync_driver/system_encryptor.h"
81 #include "components/sync_driver/user_selectable_sync_type.h"
82 #include "components/syncable_prefs/pref_service_syncable.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 sync_driver::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 (sync_driver::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(),
542 content::BrowserThread::GetMessageLoopProxyForThread(
543 content::BrowserThread::DB
),
544 content::BrowserThread::GetMessageLoopProxyForThread(
545 content::BrowserThread::FILE),
546 GetJsEventHandler(), sync_service_url_
,
547 local_device_
->GetSyncUserAgent(), credentials
,
549 scoped_ptr
<syncer::SyncManagerFactory
>(
550 new syncer::SyncManagerFactory(GetManagerType()))
552 MakeWeakHandle(weak_factory_
.GetWeakPtr()),
553 base::Bind(browser_sync::ChromeReportUnrecoverableError
),
554 network_resources_
.get(), saved_nigori_state_
.Pass());
557 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
558 if (encryption_pending())
560 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
561 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
562 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
563 return !Intersection(preferred_types
, encrypted_types
).Empty();
566 void ProfileSyncService::OnProtocolEvent(
567 const syncer::ProtocolEvent
& event
) {
568 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver
,
569 protocol_event_observers_
,
570 OnProtocolEvent(event
));
573 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
574 syncer::ModelType type
,
575 const syncer::CommitCounters
& counters
) {
576 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
577 type_debug_info_observers_
,
578 OnCommitCountersUpdated(type
, counters
));
581 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
582 syncer::ModelType type
,
583 const syncer::UpdateCounters
& counters
) {
584 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
585 type_debug_info_observers_
,
586 OnUpdateCountersUpdated(type
, counters
));
589 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
590 syncer::ModelType type
,
591 const syncer::StatusCounters
& counters
) {
592 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
593 type_debug_info_observers_
,
594 OnStatusCountersUpdated(type
, counters
));
597 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
598 syncer::ModelType type
) {
599 DCHECK(syncer::UserTypes().Has(type
));
601 if (!GetPreferredDataTypes().Has(type
)) {
602 // We can get here as datatype SyncableServices are typically wired up
603 // to the native datatype even if sync isn't enabled.
604 DVLOG(1) << "Dropping sync startup request because type "
605 << syncer::ModelTypeToString(type
) << "not enabled.";
609 // If this is a data type change after a major version update, reset the
610 // passphrase prompted state and notify observers.
611 if (IsPassphraseRequired() && passphrase_prompt_triggered_by_version_
) {
612 // The major version has changed and a local syncable change was made.
613 // Reset the passphrase prompt state.
614 passphrase_prompt_triggered_by_version_
= false;
615 sync_prefs_
.SetPassphrasePrompted(false);
619 if (backend_
.get()) {
620 DVLOG(1) << "A data type requested sync startup, but it looks like "
621 "something else beat it to the punch.";
625 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
628 void ProfileSyncService::StartUpSlowBackendComponents(
629 ProfileSyncService::BackendMode mode
) {
630 DCHECK_NE(IDLE
, mode
);
631 if (backend_mode_
== mode
) {
635 // Backend mode transition rules:
636 // * can transit from IDLE to any other non-IDLE mode.
637 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
638 // be explicitly shut down before backup/rollback starts.
639 // * can not transit out of ROLLBACK mode until rollback is finished
640 // (successfully or unsuccessfully).
641 // * can not transit out of BACKUP mode until backup is finished
642 // (successfully or unsuccessfully).
643 // * if backup is needed, can only transit to SYNC if backup is finished,
645 if (backend_mode_
== SYNC
) {
646 LOG(DFATAL
) << "Shouldn't switch from mode SYNC to mode " << mode
;
650 if (backend_mode_
== ROLLBACK
||
651 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
652 // Wait for rollback/backup to finish before start new backend.
656 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
657 if (backend_mode_
!= BACKUP
)
658 backup_rollback_controller_
->StartBackup();
662 DVLOG(1) << "Start backend mode: " << mode
;
666 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
668 ShutdownImpl(syncer::STOP_SYNC
);
671 backend_mode_
= mode
;
673 if (backend_mode_
== BACKUP
)
674 backup_start_time_
= base::Time::Now();
676 if (backend_mode_
== SYNC
&& !backup_start_time_
.is_null()) {
677 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
678 base::Time::Now() - backup_start_time_
);
679 backup_start_time_
= base::Time();
682 if (backend_mode_
== ROLLBACK
)
683 ClearBrowsingDataSinceFirstSync();
684 else if (backend_mode_
== SYNC
)
685 CheckSyncBackupIfNeeded();
687 base::FilePath sync_folder
= backend_mode_
== SYNC
?
688 base::FilePath(kSyncDataFolderName
) :
689 base::FilePath(kSyncBackupDataFolderName
);
691 invalidation::InvalidationService
* invalidator
= NULL
;
692 if (backend_mode_
== SYNC
) {
693 invalidation::ProfileInvalidationProvider
* provider
=
694 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
697 invalidator
= provider
->GetInvalidationService();
700 directory_path_
= profile_
->GetPath().Append(sync_folder
);
703 factory_
->CreateSyncBackendHost(
704 profile_
->GetDebugName(),
706 sync_prefs_
.AsWeakPtr(),
709 // Initialize the backend. Every time we start up a new SyncBackendHost,
710 // we'll want to start from a fresh SyncDB, so delete any old one that might
712 InitializeBackend(ShouldDeleteSyncFolder());
714 UpdateFirstSyncTimePref();
716 ReportPreviousSessionMemoryWarningCount();
719 void ProfileSyncService::OnGetTokenSuccess(
720 const OAuth2TokenService::Request
* request
,
721 const std::string
& access_token
,
722 const base::Time
& expiration_time
) {
723 DCHECK_EQ(access_token_request_
, request
);
724 access_token_request_
.reset();
725 access_token_
= access_token
;
726 token_receive_time_
= base::Time::Now();
727 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
729 if (sync_prefs_
.SyncHasAuthError()) {
730 sync_prefs_
.SetSyncAuthError(false);
731 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
736 if (HasSyncingBackend())
737 backend_
->UpdateCredentials(GetCredentials());
739 startup_controller_
->TryStart();
742 void ProfileSyncService::OnGetTokenFailure(
743 const OAuth2TokenService::Request
* request
,
744 const GoogleServiceAuthError
& error
) {
745 DCHECK_EQ(access_token_request_
, request
);
746 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
747 access_token_request_
.reset();
748 last_get_token_error_
= error
;
749 switch (error
.state()) {
750 case GoogleServiceAuthError::CONNECTION_FAILED
:
751 case GoogleServiceAuthError::REQUEST_CANCELED
:
752 case GoogleServiceAuthError::SERVICE_ERROR
:
753 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
754 // Transient error. Retry after some time.
755 request_access_token_backoff_
.InformOfRequest(false);
756 next_token_request_time_
= base::Time::Now() +
757 request_access_token_backoff_
.GetTimeUntilRelease();
758 request_access_token_retry_timer_
.Start(
760 request_access_token_backoff_
.GetTimeUntilRelease(),
761 base::Bind(&ProfileSyncService::RequestAccessToken
,
762 weak_factory_
.GetWeakPtr()));
766 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
767 if (!sync_prefs_
.SyncHasAuthError()) {
768 sync_prefs_
.SetSyncAuthError(true);
769 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
770 AUTH_ERROR_ENCOUNTERED
,
776 if (error
.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
) {
777 LOG(ERROR
) << "Unexpected persistent error: " << error
.ToString();
779 // Show error to user.
780 UpdateAuthErrorState(error
);
785 void ProfileSyncService::OnRefreshTokenAvailable(
786 const std::string
& account_id
) {
787 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
789 tracked_objects::ScopedTracker
tracking_profile(
790 FROM_HERE_WITH_EXPLICIT_FUNCTION(
791 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
793 if (account_id
== signin_
->GetAccountIdToUse())
794 OnRefreshTokensLoaded();
797 void ProfileSyncService::OnRefreshTokenRevoked(
798 const std::string
& account_id
) {
799 if (!IsOAuthRefreshTokenAvailable()) {
800 access_token_
.clear();
801 // The additional check around IsOAuthRefreshTokenAvailable() above
802 // prevents us sounding the alarm if we actually have a valid token but
803 // a refresh attempt failed for any variety of reasons
804 // (e.g. flaky network). It's possible the token we do have is also
805 // invalid, but in that case we should already have (or can expect) an
806 // auth error sent from the sync backend.
807 UpdateAuthErrorState(
808 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
812 void ProfileSyncService::OnRefreshTokensLoaded() {
813 // This notification gets fired when OAuth2TokenService loads the tokens
815 // Initialize the backend if sync is enabled. If the sync token was
816 // not loaded, GetCredentials() will generate invalid credentials to
817 // cause the backend to generate an auth error (crbug.com/121755).
818 if (HasSyncingBackend()) {
819 RequestAccessToken();
821 startup_controller_
->TryStart();
825 void ProfileSyncService::Shutdown() {
826 UnregisterAuthNotifications();
828 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
829 if (sync_error_controller_
) {
830 // Destroy the SyncErrorController when the service shuts down for good.
831 RemoveObserver(sync_error_controller_
.get());
832 sync_error_controller_
.reset();
836 sync_thread_
->Stop();
839 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
841 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
842 // If the backend is already shut down when a DISABLE_SYNC happens,
843 // the data directory needs to be cleaned up here.
844 sync_thread_
->task_runner()->PostTask(
845 FROM_HERE
, base::Bind(&DeleteSyncDataFolder
, directory_path_
));
850 if (reason
== syncer::ShutdownReason::STOP_SYNC
851 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
852 RemoveClientFromServer();
855 // First, we spin down the backend to stop change processing as soon as
857 base::Time shutdown_start_time
= base::Time::Now();
858 backend_
->StopSyncingForShutdown();
860 // Stop all data type controllers, if needed. Note that until Stop
861 // completes, it is possible in theory to have a ChangeProcessor apply a
862 // change from a native model. In that case, it will get applied to the sync
863 // database (which doesn't get destroyed until we destroy the backend below)
864 // as an unsynced change. That will be persisted, and committed on restart.
865 if (data_type_manager_
) {
866 if (data_type_manager_
->state() != DataTypeManager::STOPPED
) {
867 // When aborting as part of shutdown, we should expect an aborted sync
868 // configure result, else we'll dcheck when we try to read the sync error.
869 expect_sync_configuration_aborted_
= true;
870 data_type_manager_
->Stop();
872 data_type_manager_
.reset();
875 // Shutdown the migrator before the backend to ensure it doesn't pull a null
878 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
880 // Move aside the backend so nobody else tries to use it while we are
882 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
883 if (doomed_backend
) {
884 sync_thread_
= doomed_backend
->Shutdown(reason
);
885 doomed_backend
.reset();
887 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
888 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
890 weak_factory_
.InvalidateWeakPtrs();
892 if (backend_mode_
== SYNC
)
893 startup_controller_
->Reset(GetRegisteredDataTypes());
895 // Don't let backup block sync regardless backup succeeded or not.
896 if (backend_mode_
== BACKUP
)
897 backup_finished_
= true;
899 // Sync could be blocked by rollback/backup. Post task to check whether sync
900 // should start after shutting down rollback/backup backend.
901 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
902 reason
!= syncer::SWITCH_MODE_SYNC
&&
903 reason
!= syncer::BROWSER_SHUTDOWN
) {
904 base::ThreadTaskRunnerHandle::Get()->PostTask(
905 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
906 startup_controller_weak_factory_
.GetWeakPtr()));
909 // Clear various flags.
910 backend_mode_
= IDLE
;
911 expect_sync_configuration_aborted_
= false;
912 is_auth_in_progress_
= false;
913 backend_initialized_
= false;
914 cached_passphrase_
.clear();
915 encryption_pending_
= false;
916 encrypt_everything_
= false;
917 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
918 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
919 catch_up_configure_in_progress_
= false;
920 request_access_token_retry_timer_
.Stop();
921 // Revert to "no auth error".
922 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
923 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
927 // Mark this as a clean shutdown(without crash).
928 sync_prefs_
.SetCleanShutdown(true);
931 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate
) {
934 // TODO(maxbogue): Investigate whether this logic can/should be moved
935 // into ShutdownImpl or SyncBackendHost itself.
936 if (HasSyncingBackend()) {
937 backend_
->UnregisterInvalidationIds();
939 ShutdownImpl(syncer::STOP_SYNC
);
942 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
943 // PSS clients don't think we're set up while we're shutting down.
944 sync_prefs_
.ClearPreferences();
945 ClearUnrecoverableError();
946 ShutdownImpl(syncer::DISABLE_SYNC
);
951 bool ProfileSyncService::HasSyncSetupCompleted() const {
952 return sync_prefs_
.HasSyncSetupCompleted();
955 void ProfileSyncService::SetSyncSetupCompleted() {
956 sync_prefs_
.SetSyncSetupCompleted();
959 void ProfileSyncService::UpdateLastSyncedTime() {
960 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
963 void ProfileSyncService::NotifyObservers() {
964 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
968 void ProfileSyncService::NotifySyncCycleCompleted() {
969 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
970 OnSyncCycleCompleted());
973 void ProfileSyncService::ClearStaleErrors() {
974 ClearUnrecoverableError();
975 last_actionable_error_
= SyncProtocolError();
976 // Clear the data type errors as well.
977 if (data_type_manager_
.get())
978 data_type_manager_
->ResetDataTypeErrors();
981 void ProfileSyncService::ClearUnrecoverableError() {
982 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
983 unrecoverable_error_message_
.clear();
984 unrecoverable_error_location_
= tracked_objects::Location();
987 // An invariant has been violated. Transition to an error state where we try
988 // to do as little work as possible, to avoid further corruption or crashes.
989 void ProfileSyncService::OnUnrecoverableError(
990 const tracked_objects::Location
& from_here
,
991 const std::string
& message
) {
992 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
993 // interface are assumed to originate within the syncer.
994 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
995 OnUnrecoverableErrorImpl(from_here
, message
, true);
998 void ProfileSyncService::OnUnrecoverableErrorImpl(
999 const tracked_objects::Location
& from_here
,
1000 const std::string
& message
,
1001 bool delete_sync_database
) {
1002 DCHECK(HasUnrecoverableError());
1003 unrecoverable_error_message_
= message
;
1004 unrecoverable_error_location_
= from_here
;
1006 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
1007 unrecoverable_error_reason_
,
1008 ERROR_REASON_LIMIT
);
1009 std::string location
;
1010 from_here
.Write(true, true, &location
);
1012 << "Unrecoverable error detected at " << location
1013 << " -- ProfileSyncService unusable: " << message
;
1015 // Shut all data types down.
1016 base::ThreadTaskRunnerHandle::Get()->PostTask(
1019 &ProfileSyncService::ShutdownImpl
, weak_factory_
.GetWeakPtr(),
1020 delete_sync_database
? syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
1023 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
1024 if (!backend_initialized_
)
1026 data_type_manager_
->ReenableType(type
);
1029 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1030 if (backend_mode_
!= SYNC
)
1033 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1035 if (is_first_time_sync_configure_
) {
1036 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1038 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1041 base::Time on_backend_initialized_time
= base::Time::Now();
1042 base::TimeDelta delta
= on_backend_initialized_time
-
1043 startup_controller_
->start_backend_time();
1044 if (is_first_time_sync_configure_
) {
1045 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1047 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1051 void ProfileSyncService::PostBackendInitialization() {
1052 // Never get here for backup / restore.
1053 DCHECK_EQ(backend_mode_
, SYNC
);
1055 if (last_backup_time_
) {
1056 DCHECK(device_info_sync_service_
);
1057 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1060 if (protocol_event_observers_
.might_have_observers()) {
1061 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1064 if (type_debug_info_observers_
.might_have_observers()) {
1065 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1068 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1069 // backend is initialized. We want to call this before notifying observers in
1070 // case this operation affects the "passphrase required" status.
1071 ConsumeCachedPassphraseIfPossible();
1073 // The very first time the backend initializes is effectively the first time
1074 // we can say we successfully "synced". LastSyncedTime will only be null in
1075 // this case, because the pref wasn't restored on StartUp.
1076 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1077 UpdateLastSyncedTime();
1080 if (startup_controller_
->auto_start_enabled() && !IsFirstSetupInProgress()) {
1081 // Backend is initialized but we're not in sync setup, so this must be an
1082 // autostart - mark our sync setup as completed and we'll start syncing
1084 SetSyncSetupCompleted();
1087 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1088 // data type configuration because observer may flag setup as complete and
1089 // trigger data type configuration.
1090 if (HasSyncSetupCompleted()) {
1091 ConfigureDataTypeManager();
1093 DCHECK(IsFirstSetupInProgress());
1099 void ProfileSyncService::OnBackendInitialized(
1100 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1101 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1102 debug_info_listener
,
1103 const std::string
& cache_guid
,
1105 UpdateBackendInitUMA(success
);
1108 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1109 // and surface error UI to alert the user sync has stopped.
1110 // Keep the directory around for now so that on restart we will retry
1111 // again and potentially succeed in presence of transient file IO failures
1112 // or permissions issues, etc.
1114 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1115 // Unlike every other UnrecoverableError, it does not delete our sync data.
1116 // This exception made sense at the time it was implemented, but our new
1117 // directory corruption recovery mechanism makes it obsolete. By the time
1118 // we get here, we will have already tried and failed to delete the
1119 // directory. It would be no big deal if we tried to delete it again.
1120 OnInternalUnrecoverableError(FROM_HERE
,
1121 "BackendInitialize failure",
1123 ERROR_REASON_BACKEND_INIT_FAILURE
);
1127 backend_initialized_
= true;
1129 sync_js_controller_
.AttachJsBackend(js_backend
);
1130 debug_info_listener_
= debug_info_listener
;
1132 SigninClient
* signin_client
=
1133 ChromeSigninClientFactory::GetForProfile(profile_
);
1134 DCHECK(signin_client
);
1135 std::string signin_scoped_device_id
=
1136 signin_client
->GetSigninScopedDeviceId();
1138 // Initialize local device info.
1139 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1141 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1142 ConfigureDataTypeManager();
1144 PostBackendInitialization();
1147 void ProfileSyncService::OnSyncCycleCompleted() {
1148 UpdateLastSyncedTime();
1149 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1150 // Trigger garbage collection of old sessions now that we've downloaded
1151 // any new session data.
1152 base::ThreadTaskRunnerHandle::Get()->PostTask(
1153 FROM_HERE
, base::Bind(&SessionsSyncManager::DoGarbageCollection
,
1154 base::AsWeakPtr(sessions_sync_manager_
.get())));
1156 DVLOG(2) << "Notifying observers sync cycle completed";
1157 NotifySyncCycleCompleted();
1160 void ProfileSyncService::OnExperimentsChanged(
1161 const syncer::Experiments
& experiments
) {
1162 if (current_experiments_
.Matches(experiments
))
1165 current_experiments_
= experiments
;
1167 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1168 experiments
.gcm_invalidations_enabled
);
1169 profile()->GetPrefs()->SetBoolean(
1170 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1171 experiments
.wallet_sync_enabled
);
1174 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1175 is_auth_in_progress_
= false;
1176 last_auth_error_
= error
;
1183 AuthError
ConnectionStatusToAuthError(
1184 syncer::ConnectionStatus status
) {
1186 case syncer::CONNECTION_OK
:
1187 return AuthError::AuthErrorNone();
1189 case syncer::CONNECTION_AUTH_ERROR
:
1190 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1192 case syncer::CONNECTION_SERVER_ERROR
:
1193 return AuthError(AuthError::CONNECTION_FAILED
);
1197 return AuthError(AuthError::CONNECTION_FAILED
);
1203 void ProfileSyncService::OnConnectionStatusChange(
1204 syncer::ConnectionStatus status
) {
1205 connection_status_update_time_
= base::Time::Now();
1206 connection_status_
= status
;
1207 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1208 // Sync server returned error indicating that access token is invalid. It
1209 // could be either expired or access is revoked. Let's request another
1210 // access token and if access is revoked then request for token will fail
1211 // with corresponding error. If access token is repeatedly reported
1212 // invalid, there may be some issues with server, e.g. authentication
1213 // state is inconsistent on sync and token server. In that case, we
1214 // backoff token requests exponentially to avoid hammering token server
1215 // too much and to avoid getting same token due to token server's caching
1216 // policy. |request_access_token_retry_timer_| is used to backoff request
1217 // triggered by both auth error and failure talking to GAIA server.
1218 // Therefore, we're likely to reach the backoff ceiling more quickly than
1219 // you would expect from looking at the BackoffPolicy if both types of
1220 // errors happen. We shouldn't receive two errors back-to-back without
1221 // attempting a token/sync request in between, thus crank up request delay
1222 // unnecessary. This is because we won't make a sync request if we hit an
1223 // error until GAIA succeeds at sending a new token, and we won't request
1224 // a new token unless sync reports a token failure. But to be safe, don't
1225 // schedule request if this happens.
1226 if (request_access_token_retry_timer_
.IsRunning()) {
1227 // The timer to perform a request later is already running; nothing
1228 // further needs to be done at this point.
1229 } else if (request_access_token_backoff_
.failure_count() == 0) {
1230 // First time request without delay. Currently invalid token is used
1231 // to initialize sync backend and we'll always end up here. We don't
1232 // want to delay initialization.
1233 request_access_token_backoff_
.InformOfRequest(false);
1234 RequestAccessToken();
1236 request_access_token_backoff_
.InformOfRequest(false);
1237 request_access_token_retry_timer_
.Start(
1239 request_access_token_backoff_
.GetTimeUntilRelease(),
1240 base::Bind(&ProfileSyncService::RequestAccessToken
,
1241 weak_factory_
.GetWeakPtr()));
1244 // Reset backoff time after successful connection.
1245 if (status
== syncer::CONNECTION_OK
) {
1246 // Request shouldn't be scheduled at this time. But if it is, it's
1247 // possible that sync flips between OK and auth error states rapidly,
1248 // thus hammers token server. To be safe, only reset backoff delay when
1249 // no scheduled request.
1250 if (request_access_token_retry_timer_
.IsRunning()) {
1253 request_access_token_backoff_
.Reset();
1257 const GoogleServiceAuthError auth_error
=
1258 ConnectionStatusToAuthError(status
);
1259 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1260 UpdateAuthErrorState(auth_error
);
1264 void ProfileSyncService::OnPassphraseRequired(
1265 syncer::PassphraseRequiredReason reason
,
1266 const sync_pb::EncryptedData
& pending_keys
) {
1267 DCHECK(backend_
.get());
1268 DCHECK(backend_
->IsNigoriEnabled());
1270 // TODO(lipalani) : add this check to other locations as well.
1271 if (HasUnrecoverableError()) {
1272 // When unrecoverable error is detected we post a task to shutdown the
1273 // backend. The task might not have executed yet.
1277 DVLOG(1) << "Passphrase required with reason: "
1278 << syncer::PassphraseRequiredReasonToString(reason
);
1279 passphrase_required_reason_
= reason
;
1281 // TODO(stanisc): http://crbug.com/351005: Does this support USS types?
1282 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1283 if (data_type_manager_
) {
1284 // Reconfigure without the encrypted types (excluded implicitly via the
1285 // failed datatypes handler).
1286 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CRYPTO
);
1289 // Notify observers that the passphrase status may have changed.
1293 void ProfileSyncService::OnPassphraseAccepted() {
1294 DVLOG(1) << "Received OnPassphraseAccepted.";
1296 // If the pending keys were resolved via keystore, it's possible we never
1297 // consumed our cached passphrase. Clear it now.
1298 if (!cached_passphrase_
.empty())
1299 cached_passphrase_
.clear();
1301 // Reset passphrase_required_reason_ since we know we no longer require the
1302 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1303 // because that can be called by OnPassphraseRequired() if no encrypted data
1304 // types are enabled, and we don't want to clobber the true passphrase error.
1305 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1307 // Make sure the data types that depend on the passphrase are started at
1309 // TODO(stanisc): http://crbug.com/351005: Does this support USS types?
1310 const syncer::ModelTypeSet types
= GetPreferredDataTypes();
1311 if (data_type_manager_
) {
1312 // Re-enable any encrypted types if necessary.
1313 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CRYPTO
);
1319 void ProfileSyncService::OnEncryptedTypesChanged(
1320 syncer::ModelTypeSet encrypted_types
,
1321 bool encrypt_everything
) {
1322 encrypted_types_
= encrypted_types
;
1323 encrypt_everything_
= encrypt_everything
;
1324 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1325 DVLOG(1) << "Encrypted types changed to "
1326 << syncer::ModelTypeSetToString(encrypted_types_
)
1327 << " (encrypt everything is set to "
1328 << (encrypt_everything_
? "true" : "false") << ")";
1329 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1334 void ProfileSyncService::OnEncryptionComplete() {
1335 DVLOG(1) << "Encryption complete";
1336 if (encryption_pending_
&& encrypt_everything_
) {
1337 encryption_pending_
= false;
1338 // This is to nudge the integration tests when encryption is
1344 void ProfileSyncService::OnMigrationNeededForTypes(
1345 syncer::ModelTypeSet types
) {
1346 DCHECK(backend_initialized_
);
1347 DCHECK(data_type_manager_
.get());
1349 // Migrator must be valid, because we don't sync until it is created and this
1350 // callback originates from a sync cycle.
1351 migrator_
->MigrateTypes(types
);
1354 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1355 last_actionable_error_
= error
;
1356 DCHECK_NE(last_actionable_error_
.action
,
1357 syncer::UNKNOWN_ACTION
);
1358 switch (error
.action
) {
1359 case syncer::UPGRADE_CLIENT
:
1360 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1361 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1362 case syncer::STOP_AND_RESTART_SYNC
:
1363 // TODO(lipalani) : if setup in progress we want to display these
1364 // actions in the popup. The current experience might not be optimal for
1365 // the user. We just dismiss the dialog.
1366 if (startup_controller_
->IsSetupInProgress()) {
1367 RequestStop(CLEAR_DATA
);
1368 expect_sync_configuration_aborted_
= true;
1370 // Trigger an unrecoverable error to stop syncing.
1371 OnInternalUnrecoverableError(FROM_HERE
,
1372 last_actionable_error_
.error_description
,
1374 ERROR_REASON_ACTIONABLE_ERROR
);
1376 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1377 backup_rollback_controller_
->OnRollbackReceived();
1378 // Fall through to shutdown backend and sign user out.
1379 case syncer::DISABLE_SYNC_ON_CLIENT
:
1380 RequestStop(CLEAR_DATA
);
1381 #if !defined(OS_CHROMEOS)
1382 // On desktop Chrome, sign out the user after a dashboard clear.
1383 // Skip sign out on ChromeOS/Android.
1384 if (!startup_controller_
->auto_start_enabled()) {
1385 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1386 signin_metrics::SERVER_FORCED_DISABLE
);
1390 case syncer::ROLLBACK_DONE
:
1391 backup_rollback_controller_
->OnRollbackDone();
1393 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1394 // Sync disabled by domain admin. we should stop syncing until next
1396 sync_disabled_by_admin_
= true;
1397 ShutdownImpl(syncer::DISABLE_SYNC
);
1404 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1405 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1406 !backup_rollback_controller_
->StartRollback())) {
1407 // Clean up backup data for sign-out only or when rollback is disabled.
1409 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1410 // Shut down ROLLBACK backend and delete backup DB.
1411 ShutdownImpl(syncer::DISABLE_SYNC
);
1412 sync_prefs_
.ClearFirstSyncTime();
1416 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1417 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) {
1418 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1419 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1420 switches::kSyncEnableClearDataOnPassphraseEncryption
))
1423 // At this point the user has set a custom passphrase and we have received the
1424 // updated nigori state. Time to cache the nigori state, and catch up the
1425 // active data types.
1426 sync_prefs_
.SetSavedNigoriStateForPassphraseEncryptionTransition(
1428 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(true);
1429 BeginConfigureCatchUpBeforeClear();
1432 void ProfileSyncService::BeginConfigureCatchUpBeforeClear() {
1433 DCHECK_EQ(backend_mode_
, SYNC
);
1434 DCHECK(data_type_manager_
);
1435 DCHECK(!saved_nigori_state_
);
1436 saved_nigori_state_
=
1437 sync_prefs_
.GetSavedNigoriStateForPassphraseEncryptionTransition().Pass();
1438 const syncer::ModelTypeSet types
= GetActiveDataTypes();
1439 catch_up_configure_in_progress_
= true;
1440 data_type_manager_
->Configure(types
, syncer::CONFIGURE_REASON_CATCH_UP
);
1443 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() {
1444 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1445 backend_
->ClearServerData(base::Bind(
1446 &ProfileSyncService::OnClearServerDataDone
, weak_factory_
.GetWeakPtr()));
1449 void ProfileSyncService::OnClearServerDataDone() {
1450 DCHECK(sync_prefs_
.GetPassphraseEncryptionTransitionInProgress());
1451 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(false);
1453 // Call to ClearServerData generates new keystore key on the server. This
1454 // makes keystore bootstrap token invalid. Let's clear it from preferences.
1455 sync_prefs_
.SetKeystoreEncryptionBootstrapToken(std::string());
1457 // Shutdown sync, delete the Directory, then restart, restoring the cached
1459 ShutdownImpl(syncer::DISABLE_SYNC
);
1460 startup_controller_
->TryStart();
1463 void ProfileSyncService::OnConfigureDone(
1464 const DataTypeManager::ConfigureResult
& result
) {
1465 configure_status_
= result
.status
;
1466 data_type_status_table_
= result
.data_type_status_table
;
1468 if (backend_mode_
!= SYNC
) {
1469 if (configure_status_
== DataTypeManager::OK
) {
1470 StartSyncingWithServer();
1472 // Backup is done after models are associated.
1473 if (backend_mode_
== BACKUP
)
1474 backup_finished_
= true;
1476 // Asynchronously check whether sync needs to start.
1477 base::ThreadTaskRunnerHandle::Get()->PostTask(
1478 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1479 startup_controller_weak_factory_
.GetWeakPtr()));
1480 } else if (!expect_sync_configuration_aborted_
) {
1481 DVLOG(1) << "Backup/rollback backend failed to configure.";
1482 ShutdownImpl(syncer::STOP_SYNC
);
1488 // We should have cleared our cached passphrase before we get here (in
1489 // OnBackendInitialized()).
1490 DCHECK(cached_passphrase_
.empty());
1492 if (!sync_configure_start_time_
.is_null()) {
1493 if (result
.status
== DataTypeManager::OK
) {
1494 base::Time sync_configure_stop_time
= base::Time::Now();
1495 base::TimeDelta delta
= sync_configure_stop_time
-
1496 sync_configure_start_time_
;
1497 if (is_first_time_sync_configure_
) {
1498 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1500 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1504 sync_configure_start_time_
= base::Time();
1507 // Notify listeners that configuration is done.
1508 content::NotificationService::current()->Notify(
1509 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1510 content::Source
<ProfileSyncService
>(this),
1511 content::NotificationService::NoDetails());
1513 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1514 // The possible status values:
1515 // ABORT - Configuration was aborted. This is not an error, if
1516 // initiated by user.
1517 // OK - Some or all types succeeded.
1518 // Everything else is an UnrecoverableError. So treat it as such.
1520 // First handle the abort case.
1521 if (configure_status_
== DataTypeManager::ABORTED
&&
1522 expect_sync_configuration_aborted_
) {
1523 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1524 expect_sync_configuration_aborted_
= false;
1528 // Handle unrecoverable error.
1529 if (configure_status_
!= DataTypeManager::OK
) {
1530 // Something catastrophic had happened. We should only have one
1531 // error representing it.
1532 syncer::SyncError error
=
1533 data_type_status_table_
.GetUnrecoverableError();
1534 DCHECK(error
.IsSet());
1535 std::string message
=
1536 "Sync configuration failed with status " +
1537 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1539 syncer::ModelTypeSetToString(
1540 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1541 ": " + error
.message();
1542 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1543 OnInternalUnrecoverableError(error
.location(),
1546 ERROR_REASON_CONFIGURATION_FAILURE
);
1550 DCHECK_EQ(DataTypeManager::OK
, configure_status_
);
1552 // We should never get in a state where we have no encrypted datatypes
1553 // enabled, and yet we still think we require a passphrase for decryption.
1554 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1555 !IsEncryptedDatatypeEnabled()));
1557 // This must be done before we start syncing with the server to avoid
1558 // sending unencrypted data up on a first time sync.
1559 if (encryption_pending_
)
1560 backend_
->EnableEncryptEverything();
1563 if (migrator_
.get() &&
1564 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1565 // Migration in progress. Let the migrator know we just finished
1566 // configuring something. It will be up to the migrator to call
1567 // StartSyncingWithServer() if migration is now finished.
1568 migrator_
->OnConfigureDone(result
);
1572 if (catch_up_configure_in_progress_
) {
1573 catch_up_configure_in_progress_
= false;
1574 ClearAndRestartSyncForPassphraseEncryption();
1578 StartSyncingWithServer();
1581 void ProfileSyncService::OnConfigureStart() {
1582 sync_configure_start_time_
= base::Time::Now();
1586 ProfileSyncService::SyncStatusSummary
1587 ProfileSyncService::QuerySyncStatusSummary() {
1588 if (HasUnrecoverableError()) {
1589 return UNRECOVERABLE_ERROR
;
1590 } else if (!backend_
) {
1592 } else if (backend_mode_
== BACKUP
) {
1593 return BACKUP_USER_DATA
;
1594 } else if (backend_mode_
== ROLLBACK
) {
1595 return ROLLBACK_USER_DATA
;
1596 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1597 return SETUP_INCOMPLETE
;
1598 } else if (backend_
&& HasSyncSetupCompleted() && data_type_manager_
&&
1599 data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1600 return DATATYPES_NOT_INITIALIZED
;
1601 } else if (IsSyncActive()) {
1604 return UNKNOWN_ERROR
;
1607 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1608 SyncStatusSummary status
= QuerySyncStatusSummary();
1610 std::string config_status_str
=
1611 configure_status_
!= DataTypeManager::UNKNOWN
?
1612 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1615 case UNRECOVERABLE_ERROR
:
1616 return "Unrecoverable error detected";
1618 return "Syncing not enabled";
1619 case SETUP_INCOMPLETE
:
1620 return "First time sync setup incomplete";
1621 case DATATYPES_NOT_INITIALIZED
:
1622 return "Datatypes not fully initialized";
1624 return "Sync service initialized";
1625 case BACKUP_USER_DATA
:
1626 return "Backing-up user data. Status: " + config_status_str
;
1627 case ROLLBACK_USER_DATA
:
1628 return "Restoring user data. Status: " + config_status_str
;
1630 return "Status unknown: Internal error?";
1634 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1635 return startup_controller_
->GetBackendInitializationStateString();
1638 bool ProfileSyncService::auto_start_enabled() const {
1639 return startup_controller_
->auto_start_enabled();
1642 bool ProfileSyncService::IsSetupInProgress() const {
1643 return startup_controller_
->IsSetupInProgress();
1646 bool ProfileSyncService::QueryDetailedSyncStatus(
1647 SyncBackendHost::Status
* result
) {
1648 if (backend_
.get() && backend_initialized_
) {
1649 *result
= backend_
->GetDetailedStatus();
1652 SyncBackendHost::Status status
;
1653 status
.sync_protocol_error
= last_actionable_error_
;
1659 const AuthError
& ProfileSyncService::GetAuthError() const {
1660 return last_auth_error_
;
1663 bool ProfileSyncService::IsFirstSetupInProgress() const {
1664 return !HasSyncSetupCompleted() && startup_controller_
->IsSetupInProgress();
1667 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1668 // This method is a no-op if |setup_in_progress_| remains unchanged.
1669 if (startup_controller_
->IsSetupInProgress() == setup_in_progress
)
1672 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1673 if (!setup_in_progress
&& IsBackendInitialized())
1674 ReconfigureDatatypeManager();
1678 bool ProfileSyncService::IsSyncAllowed() const {
1679 return IsSyncAllowedByFlag() && !IsManaged();
1682 bool ProfileSyncService::IsSyncActive() const {
1683 return backend_initialized_
&& backend_mode_
== SYNC
&& data_type_manager_
&&
1684 data_type_manager_
->state() != DataTypeManager::STOPPED
;
1687 bool ProfileSyncService::IsSignedIn() const {
1688 // Sync is logged in if there is a non-empty effective account id.
1689 return !signin_
->GetAccountIdToUse().empty();
1692 bool ProfileSyncService::IsBackendInitialized() const {
1693 return backend_initialized_
;
1696 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1697 return backend_mode_
;
1700 bool ProfileSyncService::ConfigurationDone() const {
1701 return data_type_manager_
&&
1702 data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1705 bool ProfileSyncService::waiting_for_auth() const {
1706 return is_auth_in_progress_
;
1709 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1710 return current_experiments_
;
1713 bool ProfileSyncService::HasUnrecoverableError() const {
1714 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1717 bool ProfileSyncService::IsPassphraseRequired() const {
1718 return passphrase_required_reason_
!=
1719 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1722 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1723 // If there is an encrypted datatype enabled and we don't have the proper
1724 // passphrase, we must prompt the user for a passphrase. The only way for the
1725 // user to avoid entering their passphrase is to disable the encrypted types.
1726 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1729 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1730 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1731 if (last_synced_time
.is_null())
1732 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1734 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1736 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1737 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1739 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1740 ui::TimeFormat::LENGTH_SHORT
,
1741 time_since_last_sync
);
1744 void ProfileSyncService::UpdateSelectedTypesHistogram(
1745 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1746 if (!HasSyncSetupCompleted() ||
1747 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1748 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1751 // Only log the data types that are shown in the sync settings ui.
1752 // Note: the order of these types must match the ordering of
1753 // the respective types in ModelType
1754 const sync_driver::user_selectable_type::UserSelectableSyncType
1755 user_selectable_types
[] = {
1756 sync_driver::user_selectable_type::BOOKMARKS
,
1757 sync_driver::user_selectable_type::PREFERENCES
,
1758 sync_driver::user_selectable_type::PASSWORDS
,
1759 sync_driver::user_selectable_type::AUTOFILL
,
1760 sync_driver::user_selectable_type::THEMES
,
1761 sync_driver::user_selectable_type::TYPED_URLS
,
1762 sync_driver::user_selectable_type::EXTENSIONS
,
1763 sync_driver::user_selectable_type::APPS
,
1764 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1765 sync_driver::user_selectable_type::PROXY_TABS
,
1768 static_assert(36 == syncer::MODEL_TYPE_COUNT
,
1769 "custom config histogram must be updated");
1771 if (!sync_everything
) {
1772 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1774 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1775 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1777 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1779 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1781 const syncer::ModelType type
= it
.Get();
1782 if (chosen_types
.Has(type
) &&
1783 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1784 // Selected type has changed - log it.
1785 UMA_HISTOGRAM_ENUMERATION(
1787 user_selectable_types
[i
],
1788 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1794 #if defined(OS_CHROMEOS)
1795 void ProfileSyncService::RefreshSpareBootstrapToken(
1796 const std::string
& passphrase
) {
1797 sync_driver::SystemEncryptor encryptor
;
1798 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1799 // The first 2 params (hostname and username) doesn't have any effect here.
1800 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1802 std::string bootstrap_token
;
1803 if (!temp_cryptographer
.AddKey(key_params
)) {
1804 NOTREACHED() << "Failed to add key to cryptographer.";
1806 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1807 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1811 void ProfileSyncService::OnUserChoseDatatypes(
1812 bool sync_everything
,
1813 syncer::ModelTypeSet chosen_types
) {
1814 if (!backend_
.get() && !HasUnrecoverableError()) {
1819 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1820 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1822 if (data_type_manager_
)
1823 data_type_manager_
->ResetDataTypeErrors();
1824 ChangePreferredDataTypes(chosen_types
);
1827 void ProfileSyncService::ChangePreferredDataTypes(
1828 syncer::ModelTypeSet preferred_types
) {
1830 DVLOG(1) << "ChangePreferredDataTypes invoked";
1831 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1832 // Will only enable those types that are registered and preferred.
1833 sync_prefs_
.SetPreferredDataTypes(registered_types
, preferred_types
);
1835 // Now reconfigure the DTM.
1836 ReconfigureDatatypeManager();
1839 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1840 if (!IsSyncActive() || !ConfigurationDone())
1841 return syncer::ModelTypeSet();
1842 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1843 const syncer::ModelTypeSet failed_types
=
1844 data_type_status_table_
.GetFailedTypes();
1845 return Difference(preferred_types
, failed_types
);
1848 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1849 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1850 const syncer::ModelTypeSet preferred_types
=
1851 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1852 const syncer::ModelTypeSet enforced_types
=
1853 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1854 return Union(preferred_types
, enforced_types
);
1857 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1858 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1859 // we'll need another way to distinguish user-choosable types from
1860 // programmatically-enabled types.
1861 return GetDataTypesFromPreferenceProviders();
1864 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1865 syncer::ModelTypeSet registered_types
;
1866 // The data_type_controllers_ are determined by command-line flags;
1867 // that's effectively what controls the values returned here.
1868 for (DataTypeController::TypeMap::const_iterator it
=
1869 data_type_controllers_
.begin();
1870 it
!= data_type_controllers_
.end(); ++it
) {
1871 registered_types
.Put(it
->first
);
1873 return registered_types
;
1876 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1877 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1878 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1879 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1882 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1883 return backend_
->GetPassphraseType();
1886 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1887 return backend_
->GetExplicitPassphraseTime();
1890 bool ProfileSyncService::IsCryptographerReady(
1891 const syncer::BaseTransaction
* trans
) const {
1892 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1895 void ProfileSyncService::ConfigureDataTypeManager() {
1896 // Don't configure datatypes if the setup UI is still on the screen - this
1897 // is to help multi-screen setting UIs (like iOS) where they don't want to
1898 // start syncing data until the user is done configuring encryption options,
1899 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1900 // SetSetupInProgress(false).
1901 if (backend_mode_
== SYNC
&& startup_controller_
->IsSetupInProgress())
1904 bool restart
= false;
1905 if (!data_type_manager_
) {
1907 data_type_manager_
.reset(factory_
->CreateDataTypeManager(
1908 debug_info_listener_
, &data_type_controllers_
, this, backend_
.get(),
1911 // We create the migrator at the same time.
1912 migrator_
.reset(new browser_sync::BackendMigrator(
1913 profile_
->GetDebugName(), GetUserShare(), this,
1914 data_type_manager_
.get(),
1915 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1916 base::Unretained(this))));
1919 syncer::ModelTypeSet types
;
1920 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1921 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1922 types
= syncer::BackupTypes();
1923 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1925 types
= GetPreferredDataTypes();
1926 if (!HasSyncSetupCompleted()) {
1927 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
1928 } else if (restart
) {
1929 // Datatype downloads on restart are generally due to newly supported
1930 // datatypes (although it's also possible we're picking up where a failed
1931 // previous configuration left off).
1932 // TODO(sync): consider detecting configuration recovery and setting
1933 // the reason here appropriately.
1934 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
1936 // The user initiated a reconfiguration (either to add or remove types).
1937 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
1941 data_type_manager_
->Configure(types
, reason
);
1944 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
1945 if (backend_
.get() && backend_initialized_
) {
1946 return backend_
->GetUserShare();
1952 syncer::sessions::SyncSessionSnapshot
1953 ProfileSyncService::GetLastSessionSnapshot() const {
1955 return backend_
->GetLastSessionSnapshot();
1956 return syncer::sessions::SyncSessionSnapshot();
1959 bool ProfileSyncService::HasUnsyncedItems() const {
1960 if (HasSyncingBackend() && backend_initialized_
) {
1961 return backend_
->HasUnsyncedItems();
1967 browser_sync::BackendMigrator
*
1968 ProfileSyncService::GetBackendMigratorForTest() {
1969 return migrator_
.get();
1972 void ProfileSyncService::GetModelSafeRoutingInfo(
1973 syncer::ModelSafeRoutingInfo
* out
) const {
1974 if (backend_
.get() && backend_initialized_
) {
1975 backend_
->GetModelSafeRoutingInfo(out
);
1981 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
1982 scoped_ptr
<base::ListValue
> result(new base::ListValue());
1984 if (!backend_
.get() || !backend_initialized_
) {
1985 return result
.release();
1988 DataTypeStatusTable::TypeErrorMap error_map
=
1989 data_type_status_table_
.GetAllErrors();
1990 ModelTypeSet active_types
;
1991 ModelTypeSet passive_types
;
1992 ModelSafeRoutingInfo routing_info
;
1993 backend_
->GetModelSafeRoutingInfo(&routing_info
);
1994 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
1995 it
!= routing_info
.end(); ++it
) {
1996 if (it
->second
== syncer::GROUP_PASSIVE
) {
1997 passive_types
.Put(it
->first
);
1999 active_types
.Put(it
->first
);
2003 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2004 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2005 ModelTypeSet registered
= GetRegisteredDataTypes();
2006 scoped_ptr
<base::DictionaryValue
> type_status_header(
2007 new base::DictionaryValue());
2009 type_status_header
->SetString("name", "Model Type");
2010 type_status_header
->SetString("status", "header");
2011 type_status_header
->SetString("value", "Group Type");
2012 type_status_header
->SetString("num_entries", "Total Entries");
2013 type_status_header
->SetString("num_live", "Live Entries");
2014 result
->Append(type_status_header
.release());
2016 scoped_ptr
<base::DictionaryValue
> type_status
;
2017 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2018 ModelType type
= it
.Get();
2020 type_status
.reset(new base::DictionaryValue());
2021 type_status
->SetString("name", ModelTypeToString(type
));
2023 if (error_map
.find(type
) != error_map
.end()) {
2024 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2025 DCHECK(error
.IsSet());
2026 switch (error
.GetSeverity()) {
2027 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2028 std::string error_text
= "Error: " + error
.location().ToString() +
2029 ", " + error
.GetMessagePrefix() + error
.message();
2030 type_status
->SetString("status", "error");
2031 type_status
->SetString("value", error_text
);
2034 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2035 type_status
->SetString("status", "disabled");
2036 type_status
->SetString("value", error
.message());
2039 NOTREACHED() << "Unexpected error severity.";
2042 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2043 // Show a proxy type in "ok" state unless it is disabled by user.
2044 DCHECK(!throttled_types
.Has(type
));
2045 type_status
->SetString("status", "ok");
2046 type_status
->SetString("value", "Passive");
2047 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2048 type_status
->SetString("status", "warning");
2049 type_status
->SetString("value", "Passive, Throttled");
2050 } else if (passive_types
.Has(type
)) {
2051 type_status
->SetString("status", "warning");
2052 type_status
->SetString("value", "Passive");
2053 } else if (throttled_types
.Has(type
)) {
2054 type_status
->SetString("status", "warning");
2055 type_status
->SetString("value", "Throttled");
2056 } else if (active_types
.Has(type
)) {
2057 type_status
->SetString("status", "ok");
2058 type_status
->SetString("value", "Active: " +
2059 ModelSafeGroupToString(routing_info
[type
]));
2061 type_status
->SetString("status", "warning");
2062 type_status
->SetString("value", "Disabled by User");
2065 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2066 detailed_status
.num_to_delete_entries_by_type
[type
];
2067 type_status
->SetInteger("num_entries",
2068 detailed_status
.num_entries_by_type
[type
]);
2069 type_status
->SetInteger("num_live", live_count
);
2071 result
->Append(type_status
.release());
2073 return result
.release();
2076 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2079 backend_
->DeactivateDataType(type
);
2082 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2083 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2084 // If the backend isn't running yet, OnBackendInitialized() will call this
2085 // method again after the backend starts up.
2086 if (cached_passphrase_
.empty() || !IsBackendInitialized())
2089 // Backend is up and running, so we can consume the cached passphrase.
2090 std::string passphrase
= cached_passphrase_
;
2091 cached_passphrase_
.clear();
2093 // If we need a passphrase to decrypt data, try the cached passphrase.
2094 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2095 if (SetDecryptionPassphrase(passphrase
)) {
2096 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2101 // If we get here, we don't have pending keys (or at least, the passphrase
2102 // doesn't decrypt them) - just try to re-encrypt using the encryption
2104 if (!IsUsingSecondaryPassphrase())
2105 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2108 void ProfileSyncService::RequestAccessToken() {
2109 // Only one active request at a time.
2110 if (access_token_request_
!= NULL
)
2112 request_access_token_retry_timer_
.Stop();
2113 OAuth2TokenService::ScopeSet oauth2_scopes
;
2114 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2116 // Invalidate previous token, otherwise token service will return the same
2118 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2119 if (!access_token_
.empty()) {
2120 oauth2_token_service_
->InvalidateAccessToken(account_id
, oauth2_scopes
,
2124 access_token_
.clear();
2126 token_request_time_
= base::Time::Now();
2127 token_receive_time_
= base::Time();
2128 next_token_request_time_
= base::Time();
2129 access_token_request_
=
2130 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2133 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2134 PassphraseType type
) {
2135 // This should only be called when the backend has been initialized.
2136 DCHECK(IsBackendInitialized());
2137 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2138 "Data is already encrypted using an explicit passphrase";
2139 DCHECK(!(type
== EXPLICIT
&&
2140 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2141 "Can not set explicit passphrase when decryption is needed.";
2143 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2144 << " passphrase for encryption.";
2145 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2146 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2147 // keys. Hence, as long as we're not trying to do an invalid passphrase
2148 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2149 // will succeed. If for some reason a new encryption key arrives via
2150 // sync later, the SBH will trigger another OnPassphraseRequired().
2151 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2154 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2157 bool ProfileSyncService::SetDecryptionPassphrase(
2158 const std::string
& passphrase
) {
2159 if (IsPassphraseRequired()) {
2160 DVLOG(1) << "Setting passphrase for decryption.";
2161 bool result
= backend_
->SetDecryptionPassphrase(passphrase
);
2162 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result
);
2165 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2166 "IsPassphraseRequired() is false.";
2171 bool ProfileSyncService::IsEncryptEverythingAllowed() const {
2172 return encrypt_everything_allowed_
;
2175 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2176 DCHECK(allowed
|| !IsBackendInitialized() || !IsEncryptEverythingEnabled());
2177 encrypt_everything_allowed_
= allowed
;
2180 void ProfileSyncService::EnableEncryptEverything() {
2181 DCHECK(IsEncryptEverythingAllowed());
2183 // Tests override IsBackendInitialized() to always return true, so we
2184 // must check that instead of |backend_initialized_|.
2185 // TODO(akalin): Fix the above. :/
2186 DCHECK(IsBackendInitialized());
2187 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2188 // problems around cancelling encryption in the background (crbug.com/119649).
2189 if (!encrypt_everything_
)
2190 encryption_pending_
= true;
2193 bool ProfileSyncService::encryption_pending() const {
2194 // We may be called during the setup process before we're
2195 // initialized (via IsEncryptedDatatypeEnabled and
2196 // IsPassphraseRequiredForDecryption).
2197 return encryption_pending_
;
2200 bool ProfileSyncService::IsEncryptEverythingEnabled() const {
2201 DCHECK(backend_initialized_
);
2202 return encrypt_everything_
|| encryption_pending_
;
2205 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2206 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2207 // We may be called during the setup process before we're
2208 // initialized. In this case, we default to the sensitive types.
2209 return encrypted_types_
;
2212 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2213 if (is_sync_managed
) {
2214 StopImpl(CLEAR_DATA
);
2216 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2217 startup_controller_
->TryStart();
2221 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2222 const std::string
& username
,
2223 const std::string
& password
) {
2224 if (IsSyncRequested() && !password
.empty()) {
2225 cached_passphrase_
= password
;
2226 // Try to consume the passphrase we just cached. If the sync backend
2227 // is not running yet, the passphrase will remain cached until the
2228 // backend starts up.
2229 ConsumeCachedPassphraseIfPossible();
2231 #if defined(OS_CHROMEOS)
2232 RefreshSpareBootstrapToken(password
);
2234 if (!IsBackendInitialized() || GetAuthError().state() != AuthError::NONE
) {
2235 // Track the fact that we're still waiting for auth to complete.
2236 is_auth_in_progress_
= true;
2240 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2241 const std::string
& username
) {
2242 sync_disabled_by_admin_
= false;
2243 RequestStop(CLEAR_DATA
);
2245 if (sync_driver::BackupRollbackController::IsBackupEnabled()) {
2246 need_backup_
= true;
2247 backup_finished_
= false;
2251 void ProfileSyncService::AddObserver(
2252 sync_driver::SyncServiceObserver
* observer
) {
2253 observers_
.AddObserver(observer
);
2256 void ProfileSyncService::RemoveObserver(
2257 sync_driver::SyncServiceObserver
* observer
) {
2258 observers_
.RemoveObserver(observer
);
2261 void ProfileSyncService::AddProtocolEventObserver(
2262 browser_sync::ProtocolEventObserver
* observer
) {
2263 protocol_event_observers_
.AddObserver(observer
);
2264 if (HasSyncingBackend()) {
2265 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2269 void ProfileSyncService::RemoveProtocolEventObserver(
2270 browser_sync::ProtocolEventObserver
* observer
) {
2271 protocol_event_observers_
.RemoveObserver(observer
);
2272 if (HasSyncingBackend() &&
2273 !protocol_event_observers_
.might_have_observers()) {
2274 backend_
->DisableProtocolEventForwarding();
2278 void ProfileSyncService::AddTypeDebugInfoObserver(
2279 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2280 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2281 if (type_debug_info_observers_
.might_have_observers() &&
2282 backend_initialized_
) {
2283 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2287 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2288 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2289 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2290 if (!type_debug_info_observers_
.might_have_observers() &&
2291 backend_initialized_
) {
2292 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2296 void ProfileSyncService::AddPreferenceProvider(
2297 SyncTypePreferenceProvider
* provider
) {
2298 DCHECK(!HasPreferenceProvider(provider
))
2299 << "Providers may only be added once!";
2300 preference_providers_
.insert(provider
);
2303 void ProfileSyncService::RemovePreferenceProvider(
2304 SyncTypePreferenceProvider
* provider
) {
2305 DCHECK(HasPreferenceProvider(provider
))
2306 << "Only providers that have been added before can be removed!";
2307 preference_providers_
.erase(provider
);
2310 bool ProfileSyncService::HasPreferenceProvider(
2311 SyncTypePreferenceProvider
* provider
) const {
2312 return preference_providers_
.count(provider
) > 0;
2317 class GetAllNodesRequestHelper
2318 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2320 GetAllNodesRequestHelper(
2321 syncer::ModelTypeSet requested_types
,
2322 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2324 void OnReceivedNodesForTypes(
2325 const std::vector
<syncer::ModelType
>& types
,
2326 ScopedVector
<base::ListValue
> scoped_node_lists
);
2329 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2330 virtual ~GetAllNodesRequestHelper();
2332 scoped_ptr
<base::ListValue
> result_accumulator_
;
2334 syncer::ModelTypeSet awaiting_types_
;
2335 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2338 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2339 syncer::ModelTypeSet requested_types
,
2340 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2341 : result_accumulator_(new base::ListValue()),
2342 awaiting_types_(requested_types
),
2343 callback_(callback
) {}
2345 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2346 if (!awaiting_types_
.Empty()) {
2348 << "GetAllNodesRequest deleted before request was fulfilled. "
2349 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2353 // Called when the set of nodes for a type or set of types has been returned.
2355 // The nodes for several types can be returned at the same time by specifying
2356 // their types in the |types| array, and putting their results at the
2357 // correspnding indices in the |scoped_node_lists|.
2358 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2359 const std::vector
<syncer::ModelType
>& types
,
2360 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2361 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2363 // Take unsafe ownership of the node list.
2364 std::vector
<base::ListValue
*> node_lists
;
2365 scoped_node_lists
.release(&node_lists
);
2367 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2368 const ModelType type
= types
[i
];
2369 base::ListValue
* node_list
= node_lists
[i
];
2371 // Add these results to our list.
2372 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2373 type_dict
->SetString("type", ModelTypeToString(type
));
2374 type_dict
->Set("nodes", node_list
);
2375 result_accumulator_
->Append(type_dict
.release());
2377 // Remember that this part of the request is satisfied.
2378 awaiting_types_
.Remove(type
);
2381 if (awaiting_types_
.Empty()) {
2382 callback_
.Run(result_accumulator_
.Pass());
2389 void ProfileSyncService::GetAllNodes(
2390 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2391 // TODO(stanisc): crbug.com/328606: Make this work for USS datatypes.
2392 ModelTypeSet all_types
= GetRegisteredDataTypes();
2393 all_types
.PutAll(syncer::ControlTypes());
2394 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2395 new GetAllNodesRequestHelper(all_types
, callback
);
2397 if (!backend_initialized_
) {
2398 // If there's no backend available to fulfill the request, handle it here.
2399 ScopedVector
<base::ListValue
> empty_results
;
2400 std::vector
<ModelType
> type_vector
;
2401 for (ModelTypeSet::Iterator it
= all_types
.First(); it
.Good(); it
.Inc()) {
2402 type_vector
.push_back(it
.Get());
2403 empty_results
.push_back(new base::ListValue());
2405 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2407 backend_
->GetAllNodesForTypes(
2409 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2413 bool ProfileSyncService::HasObserver(
2414 const sync_driver::SyncServiceObserver
* observer
) const {
2415 return observers_
.HasObserver(observer
);
2418 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2419 return sync_js_controller_
.AsWeakPtr();
2422 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2423 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2427 bool ProfileSyncService::IsSyncAllowedByFlag() {
2428 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2429 switches::kDisableSync
);
2432 bool ProfileSyncService::IsManaged() const {
2433 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2436 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate
) {
2437 sync_prefs_
.SetSyncRequested(false);
2438 StopImpl(data_fate
);
2441 bool ProfileSyncService::IsSyncRequested() const {
2442 return sync_prefs_
.IsSyncRequested();
2445 SigninManagerBase
* ProfileSyncService::signin() const {
2448 return signin_
->GetOriginal();
2451 void ProfileSyncService::RequestStart() {
2453 sync_prefs_
.SetSyncRequested(true);
2454 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2455 startup_controller_
->TryStart();
2458 void ProfileSyncService::ReconfigureDatatypeManager() {
2459 // If we haven't initialized yet, don't configure the DTM as it could cause
2460 // association to start before a Directory has even been created.
2461 if (backend_initialized_
) {
2462 DCHECK(backend_
.get());
2463 ConfigureDataTypeManager();
2464 } else if (HasUnrecoverableError()) {
2465 // There is nothing more to configure. So inform the listeners,
2468 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2469 << "Unrecoverable error.";
2471 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2476 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2478 syncer::ModelTypeSet types
;
2479 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2480 preference_providers_
.begin();
2481 it
!= preference_providers_
.end();
2483 types
.PutAll((*it
)->GetPreferredDataTypes());
2488 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2490 return data_type_status_table_
;
2493 void ProfileSyncService::OnInternalUnrecoverableError(
2494 const tracked_objects::Location
& from_here
,
2495 const std::string
& message
,
2496 bool delete_sync_database
,
2497 UnrecoverableErrorReason reason
) {
2498 DCHECK(!HasUnrecoverableError());
2499 unrecoverable_error_reason_
= reason
;
2500 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2503 syncer::SyncManagerFactory::MANAGER_TYPE
2504 ProfileSyncService::GetManagerType() const {
2505 switch (backend_mode_
) {
2507 return syncer::SyncManagerFactory::NORMAL
;
2509 return syncer::SyncManagerFactory::BACKUP
;
2511 return syncer::SyncManagerFactory::ROLLBACK
;
2515 return syncer::SyncManagerFactory::NORMAL
;
2518 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2519 return request_access_token_retry_timer_
.IsRunning();
2522 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2523 return access_token_
;
2526 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2527 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2530 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2531 return sessions_sync_manager_
.get();
2534 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2535 return device_info_sync_service_
.get();
2538 sync_driver::SyncService::SyncTokenStatus
2539 ProfileSyncService::GetSyncTokenStatus() const {
2540 SyncTokenStatus status
;
2541 status
.connection_status_update_time
= connection_status_update_time_
;
2542 status
.connection_status
= connection_status_
;
2543 status
.token_request_time
= token_request_time_
;
2544 status
.token_receive_time
= token_receive_time_
;
2545 status
.last_get_token_error
= last_get_token_error_
;
2546 if (request_access_token_retry_timer_
.IsRunning())
2547 status
.next_token_request_time
= next_token_request_time_
;
2551 void ProfileSyncService::OverrideNetworkResourcesForTest(
2552 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2553 network_resources_
= network_resources
.Pass();
2556 bool ProfileSyncService::HasSyncingBackend() const {
2557 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2560 void ProfileSyncService::UpdateFirstSyncTimePref() {
2561 if (!IsSignedIn()) {
2562 // Clear if user's not signed in and rollback is done.
2563 if (backend_mode_
!= ROLLBACK
)
2564 sync_prefs_
.ClearFirstSyncTime();
2565 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2566 backend_mode_
== SYNC
) {
2567 // Set if not set before and it's syncing now.
2568 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2572 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2573 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2574 if (first_sync_time
.is_null())
2577 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2583 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2584 BrowsingDataRemover::Observer
* observer
) {
2585 browsing_data_remover_observer_
= observer
;
2588 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2589 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2593 clear_browsing_data_
= c
;
2596 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2597 DCHECK_EQ(backend_mode_
, SYNC
);
2599 #if defined(ENABLE_PRE_SYNC_BACKUP)
2600 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2601 // Check backup once a day.
2602 if (!last_backup_time_
&&
2603 (last_synced_time
.is_null() ||
2604 base::Time::Now() - last_synced_time
>=
2605 base::TimeDelta::FromDays(1))) {
2606 // If sync thread is set, need to serialize check on sync thread after
2607 // closing backup DB.
2609 sync_thread_
->task_runner()->PostTask(
2611 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2612 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2613 base::ThreadTaskRunnerHandle::Get(),
2614 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2615 weak_factory_
.GetWeakPtr())));
2617 content::BrowserThread::PostTask(
2618 content::BrowserThread::FILE, FROM_HERE
,
2619 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2620 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2621 base::ThreadTaskRunnerHandle::Get(),
2622 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2623 weak_factory_
.GetWeakPtr())));
2629 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2630 last_backup_time_
.reset(new base::Time(backup_time
));
2632 DCHECK(device_info_sync_service_
);
2633 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2636 void ProfileSyncService::TryStartSyncAfterBackup() {
2637 startup_controller_
->Reset(GetRegisteredDataTypes());
2638 startup_controller_
->TryStart();
2641 void ProfileSyncService::CleanUpBackup() {
2642 sync_prefs_
.ClearFirstSyncTime();
2643 profile_
->GetIOTaskRunner()->PostTask(
2645 base::Bind(base::IgnoreResult(base::DeleteFile
),
2646 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2650 bool ProfileSyncService::NeedBackup() const {
2651 return need_backup_
;
2654 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2655 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2658 void ProfileSyncService::FlushDirectory() const {
2659 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2660 // If sync is not initialized yet, we fail silently.
2661 if (backend_initialized_
)
2662 backend_
->FlushDirectory();
2665 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2666 return directory_path_
;
2669 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2671 return sync_thread_
->message_loop();
2672 } else if (backend_
) {
2673 return backend_
->GetSyncLoopForTesting();
2679 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types
) {
2680 if (backend_initialized_
)
2681 backend_
->RefreshTypesForTest(types
);
2684 void ProfileSyncService::RemoveClientFromServer() const {
2685 if (!backend_initialized_
) return;
2686 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2687 std::string birthday
;
2688 syncer::UserShare
* user_share
= GetUserShare();
2689 if (user_share
&& user_share
->directory
.get()) {
2690 birthday
= user_share
->directory
->store_birthday();
2692 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2693 sync_stopped_reporter_
->ReportSyncStopped(
2694 access_token_
, cache_guid
, birthday
);
2698 void ProfileSyncService::OnMemoryPressure(
2699 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
2700 if (memory_pressure_level
==
2701 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
2702 sync_prefs_
.SetMemoryPressureWarningCount(
2703 sync_prefs_
.GetMemoryPressureWarningCount() + 1);
2707 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2708 int warning_received
= sync_prefs_
.GetMemoryPressureWarningCount();
2710 if (-1 != warning_received
) {
2711 // -1 means it is new client.
2712 if (!sync_prefs_
.DidSyncShutdownCleanly()) {
2713 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2716 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2720 sync_prefs_
.SetMemoryPressureWarningCount(0);
2721 // Will set to true during a clean shutdown, so crash or something else will
2722 // remain this as false.
2723 sync_prefs_
.SetCleanShutdown(false);
2726 const GURL
& ProfileSyncService::sync_service_url() const {
2727 return sync_service_url_
;
2730 std::string
ProfileSyncService::unrecoverable_error_message() const {
2731 return unrecoverable_error_message_
;
2734 tracked_objects::Location
ProfileSyncService::unrecoverable_error_location()
2736 return unrecoverable_error_location_
;