1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/sync/profile_sync_service.h"
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browsing_data/browsing_data_helper.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
33 #include "chrome/browser/net/chrome_cookie_notification_details.h"
34 #include "chrome/browser/password_manager/password_store_factory.h"
35 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
36 #include "chrome/browser/prefs/pref_service_syncable.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/signin/about_signin_internals_factory.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
43 #include "chrome/browser/sync/glue/sync_backend_host.h"
44 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
45 #include "chrome/browser/sync/glue/sync_start_util.h"
46 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
47 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
48 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
49 #include "chrome/browser/sync/sync_type_preference_provider.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_list.h"
52 #include "chrome/browser/ui/browser_window.h"
53 #include "chrome/browser/ui/global_error/global_error_service.h"
54 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
55 #include "chrome/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/version_info/version_info_values.h"
83 #include "content/public/browser/browser_thread.h"
84 #include "content/public/browser/notification_details.h"
85 #include "content/public/browser/notification_service.h"
86 #include "content/public/browser/notification_source.h"
87 #include "net/cookies/cookie_monster.h"
88 #include "net/url_request/url_request_context_getter.h"
89 #include "sync/api/sync_error.h"
90 #include "sync/internal_api/public/configure_reason.h"
91 #include "sync/internal_api/public/http_bridge_network_resources.h"
92 #include "sync/internal_api/public/network_resources.h"
93 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
94 #include "sync/internal_api/public/shutdown_reason.h"
95 #include "sync/internal_api/public/sync_context_proxy.h"
96 #include "sync/internal_api/public/sync_encryption_handler.h"
97 #include "sync/internal_api/public/util/experiments.h"
98 #include "sync/internal_api/public/util/sync_db_util.h"
99 #include "sync/internal_api/public/util/sync_string_conversions.h"
100 #include "sync/js/js_event_details.h"
101 #include "sync/protocol/sync.pb.h"
102 #include "sync/syncable/directory.h"
103 #include "sync/util/cryptographer.h"
104 #include "ui/base/l10n/l10n_util.h"
105 #include "ui/base/l10n/time_format.h"
107 #if defined(OS_ANDROID)
108 #include "sync/internal_api/public/read_transaction.h"
111 using browser_sync::NotificationServiceSessionsRouter
;
112 using browser_sync::ProfileSyncServiceStartBehavior
;
113 using browser_sync::SessionsSyncManager
;
114 using browser_sync::SyncBackendHost
;
115 using sync_driver::ChangeProcessor
;
116 using sync_driver::DataTypeController
;
117 using sync_driver::DataTypeManager
;
118 using sync_driver::DataTypeStatusTable
;
119 using sync_driver::DeviceInfoSyncService
;
120 using syncer::ModelType
;
121 using syncer::ModelTypeSet
;
122 using syncer::JsBackend
;
123 using syncer::JsController
;
124 using syncer::JsEventDetails
;
125 using syncer::JsEventHandler
;
126 using syncer::ModelSafeRoutingInfo
;
127 using syncer::SyncCredentials
;
128 using syncer::SyncProtocolError
;
129 using syncer::WeakHandle
;
131 typedef GoogleServiceAuthError AuthError
;
133 const char kSyncUnrecoverableErrorHistogram
[] =
134 "Sync.UnrecoverableErrors";
136 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy
= {
137 // Number of initial errors (in sequence) to ignore before applying
138 // exponential back-off rules.
141 // Initial delay for exponential back-off in ms.
144 // Factor by which the waiting time will be multiplied.
147 // Fuzzing percentage. ex: 10% will spread requests randomly
148 // between 90%-100% of the calculated time.
151 // Maximum amount of time we are willing to delay our request in ms.
152 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
153 // RequestAccessToken on connection state change after backoff
154 1000 * 3600 * 4, // 4 hours.
156 // Time to keep an entry from being discarded even when it
157 // has no significant state, -1 to never discard.
160 // Don't use initial delay unless the last request was an error.
164 static const base::FilePath::CharType kSyncDataFolderName
[] =
165 FILE_PATH_LITERAL("Sync Data");
167 static const base::FilePath::CharType kSyncBackupDataFolderName
[] =
168 FILE_PATH_LITERAL("Sync Data Backup");
172 void ClearBrowsingData(BrowsingDataRemover::Observer
* observer
,
176 // BrowsingDataRemover deletes itself when it's done.
177 BrowsingDataRemover
* remover
= BrowsingDataRemover::CreateForRange(
178 profile
, start
, end
);
180 remover
->AddObserver(observer
);
181 remover
->Remove(BrowsingDataRemover::REMOVE_ALL
,
182 BrowsingDataHelper::ALL
);
184 scoped_refptr
<password_manager::PasswordStore
> password
=
185 PasswordStoreFactory::GetForProfile(profile
,
186 ServiceAccessType::EXPLICIT_ACCESS
);
187 password
->RemoveLoginsSyncedBetween(start
, end
);
190 // Perform the actual sync data folder deletion.
191 // This should only be called on the sync thread.
192 void DeleteSyncDataFolder(const base::FilePath
& directory_path
) {
193 if (base::DirectoryExists(directory_path
)) {
194 if (!base::DeleteFile(directory_path
, true))
195 LOG(DFATAL
) << "Could not delete the Sync Data folder.";
199 } // anonymous namespace
201 bool ShouldShowActionOnUI(
202 const syncer::SyncProtocolError
& error
) {
203 return (error
.action
!= syncer::UNKNOWN_ACTION
&&
204 error
.action
!= syncer::DISABLE_SYNC_ON_CLIENT
&&
205 error
.action
!= syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
);
208 ProfileSyncService::ProfileSyncService(
209 scoped_ptr
<sync_driver::SyncApiComponentFactory
> factory
,
211 scoped_ptr
<SupervisedUserSigninManagerWrapper
> signin_wrapper
,
212 ProfileOAuth2TokenService
* oauth2_token_service
,
213 ProfileSyncServiceStartBehavior start_behavior
)
214 : OAuth2TokenService::Consumer("sync"),
215 last_auth_error_(AuthError::AuthErrorNone()),
216 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED
),
217 factory_(factory
.Pass()),
219 sync_prefs_(profile_
->GetPrefs()),
221 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess(),
222 chrome::GetChannel())),
223 is_first_time_sync_configure_(false),
224 backend_initialized_(false),
225 sync_disabled_by_admin_(false),
226 is_auth_in_progress_(false),
227 signin_(signin_wrapper
.Pass()),
228 unrecoverable_error_reason_(ERROR_REASON_UNSET
),
229 expect_sync_configuration_aborted_(false),
230 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
231 encrypt_everything_allowed_(true),
232 encrypt_everything_(false),
233 encryption_pending_(false),
234 configure_status_(DataTypeManager::UNKNOWN
),
235 oauth2_token_service_(oauth2_token_service
),
236 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy
),
237 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED
),
238 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
239 network_resources_(new syncer::HttpBridgeNetworkResources
),
242 backup_finished_(false),
243 clear_browsing_data_(base::Bind(&ClearBrowsingData
)),
244 browsing_data_remover_observer_(NULL
),
245 catch_up_configure_in_progress_(false),
246 passphrase_prompt_triggered_by_version_(false),
248 startup_controller_weak_factory_(this) {
249 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
251 startup_controller_
.reset(new browser_sync::StartupController(
253 oauth2_token_service
,
256 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
257 startup_controller_weak_factory_
.GetWeakPtr(),
259 backup_rollback_controller_
.reset(new browser_sync::BackupRollbackController(
262 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
263 startup_controller_weak_factory_
.GetWeakPtr(),
265 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents
,
266 startup_controller_weak_factory_
.GetWeakPtr(),
268 syncer::SyncableService::StartSyncFlare
flare(
269 sync_start_util::GetFlareForSyncableService(profile
->GetPath()));
270 scoped_ptr
<browser_sync::LocalSessionEventRouter
> router(
271 new NotificationServiceSessionsRouter(profile
, flare
));
273 DCHECK(factory_
.get());
274 local_device_
= factory_
->CreateLocalDeviceInfoProvider();
275 sync_stopped_reporter_
.reset(
276 new browser_sync::SyncStoppedReporter(
278 local_device_
->GetSyncUserAgent(),
279 profile_
->GetRequestContext(),
280 browser_sync::SyncStoppedReporter::ResultCallback())),
281 sessions_sync_manager_
.reset(
282 new SessionsSyncManager(profile
, local_device_
.get(), router
.Pass()));
283 device_info_sync_service_
.reset(
284 new DeviceInfoSyncService(local_device_
.get()));
286 std::string last_version
= sync_prefs_
.GetLastRunVersion();
287 std::string current_version
= PRODUCT_VERSION
;
288 sync_prefs_
.SetLastRunVersion(current_version
);
290 // Check for a major version change. Note that the versions have format
291 // MAJOR.MINOR.BUILD.PATCH.
292 if (last_version
.substr(0, last_version
.find('.')) !=
293 current_version
.substr(0, current_version
.find('.'))) {
294 passphrase_prompt_triggered_by_version_
= true;
298 ProfileSyncService::~ProfileSyncService() {
299 sync_prefs_
.RemoveSyncPrefObserver(this);
300 // Shutdown() should have been called before destruction.
301 CHECK(!backend_initialized_
);
304 bool ProfileSyncService::CanSyncStart() const {
305 return IsSyncAllowed() && IsSyncRequested() && IsSignedIn();
308 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
309 if (!oauth2_token_service_
)
312 return oauth2_token_service_
->RefreshTokenIsAvailable(
313 signin_
->GetAccountIdToUse());
316 void ProfileSyncService::Initialize() {
317 // We clear this here (vs Shutdown) because we want to remember that an error
318 // happened on shutdown so we can display details (message, location) about it
322 sync_prefs_
.AddSyncPrefObserver(this);
324 // If sync isn't allowed, the only thing to do is to turn it off.
325 if (!IsSyncAllowed()) {
326 RequestStop(CLEAR_DATA
);
330 RegisterAuthNotifications();
332 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
333 // Clean up in case of previous crash / setup abort / signout.
334 StopImpl(CLEAR_DATA
);
337 TrySyncDatatypePrefRecovery();
339 #if defined(OS_CHROMEOS)
340 std::string bootstrap_token
= sync_prefs_
.GetEncryptionBootstrapToken();
341 if (bootstrap_token
.empty()) {
342 sync_prefs_
.SetEncryptionBootstrapToken(
343 sync_prefs_
.GetSpareBootstrapToken());
347 #if !defined(OS_ANDROID)
348 DCHECK(sync_error_controller_
== NULL
)
349 << "Initialize() called more than once.";
350 sync_error_controller_
.reset(new SyncErrorController(this));
351 AddObserver(sync_error_controller_
.get());
354 bool running_rollback
= false;
355 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
356 // Backup is needed if user's not signed in or signed in but previous
357 // backup didn't finish, i.e. backend didn't switch from backup to sync.
358 need_backup_
= !IsSignedIn() || sync_prefs_
.GetFirstSyncTime().is_null();
360 // Try to resume rollback if it didn't finish in last session.
361 running_rollback
= backup_rollback_controller_
->StartRollback();
363 need_backup_
= false;
366 #if defined(ENABLE_PRE_SYNC_BACKUP)
367 if (!running_rollback
&& !IsSignedIn()) {
371 DCHECK(!running_rollback
);
374 memory_pressure_listener_
.reset(new base::MemoryPressureListener(base::Bind(
375 &ProfileSyncService::OnMemoryPressure
, weak_factory_
.GetWeakPtr())));
376 startup_controller_
->Reset(GetRegisteredDataTypes());
377 startup_controller_
->TryStart();
380 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
381 DCHECK(!backend_initialized());
382 if (!HasSyncSetupCompleted())
385 // There was a bug where OnUserChoseDatatypes was not properly called on
386 // configuration (see crbug.com/154940). We detect this by checking whether
387 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
388 // completed, it means sync was not properly configured, so we manually
389 // set kSyncKeepEverythingSynced.
390 PrefService
* const pref_service
= profile_
->GetPrefs();
393 if (GetPreferredDataTypes().Size() > 1)
396 const PrefService::Preference
* keep_everything_synced
=
397 pref_service
->FindPreference(
398 sync_driver::prefs::kSyncKeepEverythingSynced
);
399 // This will be false if the preference was properly set or if it's controlled
401 if (!keep_everything_synced
->IsDefaultValue())
404 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
405 // types now, before we configure.
406 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
407 sync_prefs_
.SetKeepEverythingSynced(true);
408 syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
411 void ProfileSyncService::StartSyncingWithServer() {
412 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
414 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
415 switches::kSyncEnableClearDataOnPassphraseEncryption
) &&
416 backend_mode_
== SYNC
&&
417 sync_prefs_
.GetPassphraseEncryptionTransitionInProgress()) {
418 BeginConfigureCatchUpBeforeClear();
423 backend_
->StartSyncingWithServer();
426 void ProfileSyncService::RegisterAuthNotifications() {
427 oauth2_token_service_
->AddObserver(this);
429 signin()->AddObserver(this);
432 void ProfileSyncService::UnregisterAuthNotifications() {
434 signin()->RemoveObserver(this);
435 oauth2_token_service_
->RemoveObserver(this);
438 void ProfileSyncService::RegisterDataTypeController(
439 sync_driver::DataTypeController
* data_type_controller
) {
441 directory_data_type_controllers_
.count(data_type_controller
->type()),
443 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
444 data_type_controller
->type()));
445 directory_data_type_controllers_
[data_type_controller
->type()] =
446 data_type_controller
;
449 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type
) {
450 DCHECK_EQ(directory_data_type_controllers_
.count(type
), 0U)
451 << "Duplicate registration of type " << ModelTypeToString(type
);
453 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
454 // fixed and we have some way of telling whether or not this type should be
456 non_blocking_data_type_manager_
.RegisterType(type
, false);
459 void ProfileSyncService::InitializeNonBlockingType(
460 syncer::ModelType type
,
461 const scoped_refptr
<base::SequencedTaskRunner
>& task_runner
,
462 const base::WeakPtr
<syncer_v2::ModelTypeProcessorImpl
>& type_processor
) {
463 non_blocking_data_type_manager_
.InitializeType(
464 type
, task_runner
, type_processor
);
467 bool ProfileSyncService::IsDataTypeControllerRunning(
468 syncer::ModelType type
) const {
469 DataTypeController::TypeMap::const_iterator iter
=
470 directory_data_type_controllers_
.find(type
);
471 if (iter
== directory_data_type_controllers_
.end()) {
474 return iter
->second
->state() == DataTypeController::RUNNING
;
477 sync_driver::OpenTabsUIDelegate
* ProfileSyncService::GetOpenTabsUIDelegate() {
478 if (!IsDataTypeControllerRunning(syncer::SESSIONS
))
480 return sessions_sync_manager_
.get();
483 browser_sync::FaviconCache
* ProfileSyncService::GetFaviconCache() {
484 return sessions_sync_manager_
->GetFaviconCache();
487 browser_sync::SyncedWindowDelegatesGetter
*
488 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
489 return sessions_sync_manager_
->GetSyncedWindowDelegatesGetter();
492 sync_driver::DeviceInfoTracker
* ProfileSyncService::GetDeviceInfoTracker()
494 return device_info_sync_service_
.get();
497 sync_driver::LocalDeviceInfoProvider
*
498 ProfileSyncService::GetLocalDeviceInfoProvider() const {
499 return local_device_
.get();
502 void ProfileSyncService::GetDataTypeControllerStates(
503 DataTypeController::StateMap
* state_map
) const {
504 for (DataTypeController::TypeMap::const_iterator iter
=
505 directory_data_type_controllers_
.begin();
506 iter
!= directory_data_type_controllers_
.end();
508 (*state_map
)[iter
->first
] = iter
->second
.get()->state();
511 SyncCredentials
ProfileSyncService::GetCredentials() {
512 SyncCredentials credentials
;
513 if (backend_mode_
== SYNC
) {
514 credentials
.email
= signin_
->GetEffectiveUsername();
515 DCHECK(!credentials
.email
.empty());
516 credentials
.sync_token
= access_token_
;
518 if (credentials
.sync_token
.empty())
519 credentials
.sync_token
= "credentials_lost";
521 credentials
.scope_set
.insert(signin_
->GetSyncScopeToUse());
527 bool ProfileSyncService::ShouldDeleteSyncFolder() {
528 switch (backend_mode_
) {
530 return !HasSyncSetupCompleted();
542 void ProfileSyncService::InitializeBackend(bool delete_stale_data
) {
548 SyncCredentials credentials
= GetCredentials();
550 scoped_refptr
<net::URLRequestContextGetter
> request_context_getter(
551 profile_
->GetRequestContext());
553 if (backend_mode_
== SYNC
&& delete_stale_data
)
556 backend_
->Initialize(this, sync_thread_
.Pass(), GetJsEventHandler(),
558 local_device_
->GetSyncUserAgent(),
559 credentials
, delete_stale_data
,
560 scoped_ptr
<syncer::SyncManagerFactory
>(
561 new syncer::SyncManagerFactory(GetManagerType()))
563 MakeWeakHandle(weak_factory_
.GetWeakPtr()),
564 base::Bind(browser_sync::ChromeReportUnrecoverableError
),
565 network_resources_
.get(), saved_nigori_state_
.Pass());
568 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
569 if (encryption_pending())
571 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
572 const syncer::ModelTypeSet encrypted_types
= GetEncryptedDataTypes();
573 DCHECK(encrypted_types
.Has(syncer::PASSWORDS
));
574 return !Intersection(preferred_types
, encrypted_types
).Empty();
577 void ProfileSyncService::OnProtocolEvent(
578 const syncer::ProtocolEvent
& event
) {
579 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver
,
580 protocol_event_observers_
,
581 OnProtocolEvent(event
));
584 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
585 syncer::ModelType type
,
586 const syncer::CommitCounters
& counters
) {
587 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
588 type_debug_info_observers_
,
589 OnCommitCountersUpdated(type
, counters
));
592 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
593 syncer::ModelType type
,
594 const syncer::UpdateCounters
& counters
) {
595 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
596 type_debug_info_observers_
,
597 OnUpdateCountersUpdated(type
, counters
));
600 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
601 syncer::ModelType type
,
602 const syncer::StatusCounters
& counters
) {
603 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver
,
604 type_debug_info_observers_
,
605 OnStatusCountersUpdated(type
, counters
));
608 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
609 syncer::ModelType type
) {
610 DCHECK(syncer::UserTypes().Has(type
));
612 if (!GetPreferredDataTypes().Has(type
)) {
613 // We can get here as datatype SyncableServices are typically wired up
614 // to the native datatype even if sync isn't enabled.
615 DVLOG(1) << "Dropping sync startup request because type "
616 << syncer::ModelTypeToString(type
) << "not enabled.";
620 // If this is a data type change after a major version update, reset the
621 // passphrase prompted state and notify observers.
622 if (IsPassphraseRequired() && passphrase_prompt_triggered_by_version_
) {
623 // The major version has changed and a local syncable change was made.
624 // Reset the passphrase prompt state.
625 passphrase_prompt_triggered_by_version_
= false;
626 sync_prefs_
.SetPassphrasePrompted(false);
630 if (backend_
.get()) {
631 DVLOG(1) << "A data type requested sync startup, but it looks like "
632 "something else beat it to the punch.";
636 startup_controller_
->OnDataTypeRequestsSyncStartup(type
);
639 void ProfileSyncService::StartUpSlowBackendComponents(
640 ProfileSyncService::BackendMode mode
) {
641 DCHECK_NE(IDLE
, mode
);
642 if (backend_mode_
== mode
) {
646 // Backend mode transition rules:
647 // * can transit from IDLE to any other non-IDLE mode.
648 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
649 // be explicitly shut down before backup/rollback starts.
650 // * can not transit out of ROLLBACK mode until rollback is finished
651 // (successfully or unsuccessfully).
652 // * can not transit out of BACKUP mode until backup is finished
653 // (successfully or unsuccessfully).
654 // * if backup is needed, can only transit to SYNC if backup is finished,
656 if (backend_mode_
== SYNC
) {
657 LOG(DFATAL
) << "Shouldn't switch from mode SYNC to mode " << mode
;
661 if (backend_mode_
== ROLLBACK
||
662 (backend_mode_
== BACKUP
&& !backup_finished_
)) {
663 // Wait for rollback/backup to finish before start new backend.
667 if (mode
== SYNC
&& NeedBackup() && !backup_finished_
) {
668 if (backend_mode_
!= BACKUP
)
669 backup_rollback_controller_
->StartBackup();
673 DVLOG(1) << "Start backend mode: " << mode
;
677 ShutdownImpl(syncer::SWITCH_MODE_SYNC
);
679 ShutdownImpl(syncer::STOP_SYNC
);
682 backend_mode_
= mode
;
684 if (backend_mode_
== BACKUP
)
685 backup_start_time_
= base::Time::Now();
687 if (backend_mode_
== SYNC
&& !backup_start_time_
.is_null()) {
688 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
689 base::Time::Now() - backup_start_time_
);
690 backup_start_time_
= base::Time();
693 if (backend_mode_
== ROLLBACK
)
694 ClearBrowsingDataSinceFirstSync();
695 else if (backend_mode_
== SYNC
)
696 CheckSyncBackupIfNeeded();
698 base::FilePath sync_folder
= backend_mode_
== SYNC
?
699 base::FilePath(kSyncDataFolderName
) :
700 base::FilePath(kSyncBackupDataFolderName
);
702 invalidation::InvalidationService
* invalidator
= NULL
;
703 if (backend_mode_
== SYNC
) {
704 invalidation::ProfileInvalidationProvider
* provider
=
705 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
708 invalidator
= provider
->GetInvalidationService();
711 directory_path_
= profile_
->GetPath().Append(sync_folder
);
714 factory_
->CreateSyncBackendHost(
715 profile_
->GetDebugName(),
717 sync_prefs_
.AsWeakPtr(),
720 // Initialize the backend. Every time we start up a new SyncBackendHost,
721 // we'll want to start from a fresh SyncDB, so delete any old one that might
723 InitializeBackend(ShouldDeleteSyncFolder());
725 UpdateFirstSyncTimePref();
727 ReportPreviousSessionMemoryWarningCount();
730 void ProfileSyncService::OnGetTokenSuccess(
731 const OAuth2TokenService::Request
* request
,
732 const std::string
& access_token
,
733 const base::Time
& expiration_time
) {
734 DCHECK_EQ(access_token_request_
, request
);
735 access_token_request_
.reset();
736 access_token_
= access_token
;
737 token_receive_time_
= base::Time::Now();
738 last_get_token_error_
= GoogleServiceAuthError::AuthErrorNone();
740 if (sync_prefs_
.SyncHasAuthError()) {
741 sync_prefs_
.SetSyncAuthError(false);
742 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
747 if (HasSyncingBackend())
748 backend_
->UpdateCredentials(GetCredentials());
750 startup_controller_
->TryStart();
753 void ProfileSyncService::OnGetTokenFailure(
754 const OAuth2TokenService::Request
* request
,
755 const GoogleServiceAuthError
& error
) {
756 DCHECK_EQ(access_token_request_
, request
);
757 DCHECK_NE(error
.state(), GoogleServiceAuthError::NONE
);
758 access_token_request_
.reset();
759 last_get_token_error_
= error
;
760 switch (error
.state()) {
761 case GoogleServiceAuthError::CONNECTION_FAILED
:
762 case GoogleServiceAuthError::REQUEST_CANCELED
:
763 case GoogleServiceAuthError::SERVICE_ERROR
:
764 case GoogleServiceAuthError::SERVICE_UNAVAILABLE
: {
765 // Transient error. Retry after some time.
766 request_access_token_backoff_
.InformOfRequest(false);
767 next_token_request_time_
= base::Time::Now() +
768 request_access_token_backoff_
.GetTimeUntilRelease();
769 request_access_token_retry_timer_
.Start(
771 request_access_token_backoff_
.GetTimeUntilRelease(),
772 base::Bind(&ProfileSyncService::RequestAccessToken
,
773 weak_factory_
.GetWeakPtr()));
777 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
: {
778 if (!sync_prefs_
.SyncHasAuthError()) {
779 sync_prefs_
.SetSyncAuthError(true);
780 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
781 AUTH_ERROR_ENCOUNTERED
,
787 if (error
.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS
) {
788 LOG(ERROR
) << "Unexpected persistent error: " << error
.ToString();
790 // Show error to user.
791 UpdateAuthErrorState(error
);
796 void ProfileSyncService::OnRefreshTokenAvailable(
797 const std::string
& account_id
) {
798 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
800 tracked_objects::ScopedTracker
tracking_profile(
801 FROM_HERE_WITH_EXPLICIT_FUNCTION(
802 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
804 if (account_id
== signin_
->GetAccountIdToUse())
805 OnRefreshTokensLoaded();
808 void ProfileSyncService::OnRefreshTokenRevoked(
809 const std::string
& account_id
) {
810 if (!IsOAuthRefreshTokenAvailable()) {
811 access_token_
.clear();
812 // The additional check around IsOAuthRefreshTokenAvailable() above
813 // prevents us sounding the alarm if we actually have a valid token but
814 // a refresh attempt failed for any variety of reasons
815 // (e.g. flaky network). It's possible the token we do have is also
816 // invalid, but in that case we should already have (or can expect) an
817 // auth error sent from the sync backend.
818 UpdateAuthErrorState(
819 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED
));
823 void ProfileSyncService::OnRefreshTokensLoaded() {
824 // This notification gets fired when OAuth2TokenService loads the tokens
826 // Initialize the backend if sync is enabled. If the sync token was
827 // not loaded, GetCredentials() will generate invalid credentials to
828 // cause the backend to generate an auth error (crbug.com/121755).
829 if (HasSyncingBackend()) {
830 RequestAccessToken();
832 startup_controller_
->TryStart();
836 void ProfileSyncService::Shutdown() {
837 UnregisterAuthNotifications();
839 ShutdownImpl(syncer::BROWSER_SHUTDOWN
);
840 if (sync_error_controller_
) {
841 // Destroy the SyncErrorController when the service shuts down for good.
842 RemoveObserver(sync_error_controller_
.get());
843 sync_error_controller_
.reset();
847 sync_thread_
->Stop();
850 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason
) {
852 if (reason
== syncer::ShutdownReason::DISABLE_SYNC
&& sync_thread_
) {
853 // If the backend is already shut down when a DISABLE_SYNC happens,
854 // the data directory needs to be cleaned up here.
855 sync_thread_
->task_runner()->PostTask(
856 FROM_HERE
, base::Bind(&DeleteSyncDataFolder
, directory_path_
));
861 if (reason
== syncer::ShutdownReason::STOP_SYNC
862 || reason
== syncer::ShutdownReason::DISABLE_SYNC
) {
863 RemoveClientFromServer();
866 non_blocking_data_type_manager_
.DisconnectSyncBackend();
868 // First, we spin down the backend to stop change processing as soon as
870 base::Time shutdown_start_time
= base::Time::Now();
871 backend_
->StopSyncingForShutdown();
873 // Stop all data type controllers, if needed. Note that until Stop
874 // completes, it is possible in theory to have a ChangeProcessor apply a
875 // change from a native model. In that case, it will get applied to the sync
876 // database (which doesn't get destroyed until we destroy the backend below)
877 // as an unsynced change. That will be persisted, and committed on restart.
878 if (directory_data_type_manager_
) {
879 if (directory_data_type_manager_
->state() != DataTypeManager::STOPPED
) {
880 // When aborting as part of shutdown, we should expect an aborted sync
881 // configure result, else we'll dcheck when we try to read the sync error.
882 expect_sync_configuration_aborted_
= true;
883 directory_data_type_manager_
->Stop();
885 directory_data_type_manager_
.reset();
888 // Shutdown the migrator before the backend to ensure it doesn't pull a null
891 sync_js_controller_
.AttachJsBackend(WeakHandle
<syncer::JsBackend
>());
893 // Move aside the backend so nobody else tries to use it while we are
895 scoped_ptr
<SyncBackendHost
> doomed_backend(backend_
.release());
896 if (doomed_backend
) {
897 sync_thread_
= doomed_backend
->Shutdown(reason
);
898 doomed_backend
.reset();
900 base::TimeDelta shutdown_time
= base::Time::Now() - shutdown_start_time
;
901 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time
);
903 weak_factory_
.InvalidateWeakPtrs();
905 if (backend_mode_
== SYNC
)
906 startup_controller_
->Reset(GetRegisteredDataTypes());
908 // Don't let backup block sync regardless backup succeeded or not.
909 if (backend_mode_
== BACKUP
)
910 backup_finished_
= true;
912 // Sync could be blocked by rollback/backup. Post task to check whether sync
913 // should start after shutting down rollback/backup backend.
914 if ((backend_mode_
== ROLLBACK
|| backend_mode_
== BACKUP
) &&
915 reason
!= syncer::SWITCH_MODE_SYNC
&&
916 reason
!= syncer::BROWSER_SHUTDOWN
) {
917 base::ThreadTaskRunnerHandle::Get()->PostTask(
918 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
919 startup_controller_weak_factory_
.GetWeakPtr()));
922 // Clear various flags.
923 backend_mode_
= IDLE
;
924 expect_sync_configuration_aborted_
= false;
925 is_auth_in_progress_
= false;
926 backend_initialized_
= false;
927 cached_passphrase_
.clear();
928 encryption_pending_
= false;
929 encrypt_everything_
= false;
930 encrypted_types_
= syncer::SyncEncryptionHandler::SensitiveTypes();
931 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
932 catch_up_configure_in_progress_
= false;
933 request_access_token_retry_timer_
.Stop();
934 // Revert to "no auth error".
935 if (last_auth_error_
.state() != GoogleServiceAuthError::NONE
)
936 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
940 // Mark this as a clean shutdown(without crash).
941 sync_prefs_
.SetCleanShutdown(true);
944 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate
) {
947 // TODO(maxbogue): Investigate whether this logic can/should be moved
948 // into ShutdownImpl or SyncBackendHost itself.
949 if (HasSyncingBackend()) {
950 backend_
->UnregisterInvalidationIds();
952 ShutdownImpl(syncer::STOP_SYNC
);
955 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
956 // PSS clients don't think we're set up while we're shutting down.
957 sync_prefs_
.ClearPreferences();
958 ClearUnrecoverableError();
959 ShutdownImpl(syncer::DISABLE_SYNC
);
964 bool ProfileSyncService::HasSyncSetupCompleted() const {
965 return sync_prefs_
.HasSyncSetupCompleted();
968 void ProfileSyncService::SetSyncSetupCompleted() {
969 sync_prefs_
.SetSyncSetupCompleted();
972 void ProfileSyncService::UpdateLastSyncedTime() {
973 sync_prefs_
.SetLastSyncedTime(base::Time::Now());
976 void ProfileSyncService::NotifyObservers() {
977 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
981 void ProfileSyncService::NotifySyncCycleCompleted() {
982 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver
, observers_
,
983 OnSyncCycleCompleted());
986 void ProfileSyncService::ClearStaleErrors() {
987 ClearUnrecoverableError();
988 last_actionable_error_
= SyncProtocolError();
989 // Clear the data type errors as well.
990 if (directory_data_type_manager_
.get())
991 directory_data_type_manager_
->ResetDataTypeErrors();
995 void ProfileSyncService::ClearUnrecoverableError() {
996 unrecoverable_error_reason_
= ERROR_REASON_UNSET
;
997 unrecoverable_error_message_
.clear();
998 unrecoverable_error_location_
= tracked_objects::Location();
1001 // An invariant has been violated. Transition to an error state where we try
1002 // to do as little work as possible, to avoid further corruption or crashes.
1003 void ProfileSyncService::OnUnrecoverableError(
1004 const tracked_objects::Location
& from_here
,
1005 const std::string
& message
) {
1006 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
1007 // interface are assumed to originate within the syncer.
1008 unrecoverable_error_reason_
= ERROR_REASON_SYNCER
;
1009 OnUnrecoverableErrorImpl(from_here
, message
, true);
1012 void ProfileSyncService::OnUnrecoverableErrorImpl(
1013 const tracked_objects::Location
& from_here
,
1014 const std::string
& message
,
1015 bool delete_sync_database
) {
1016 DCHECK(HasUnrecoverableError());
1017 unrecoverable_error_message_
= message
;
1018 unrecoverable_error_location_
= from_here
;
1020 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram
,
1021 unrecoverable_error_reason_
,
1022 ERROR_REASON_LIMIT
);
1023 std::string location
;
1024 from_here
.Write(true, true, &location
);
1026 << "Unrecoverable error detected at " << location
1027 << " -- ProfileSyncService unusable: " << message
;
1029 // Shut all data types down.
1030 base::ThreadTaskRunnerHandle::Get()->PostTask(
1033 &ProfileSyncService::ShutdownImpl
, weak_factory_
.GetWeakPtr(),
1034 delete_sync_database
? syncer::DISABLE_SYNC
: syncer::STOP_SYNC
));
1037 void ProfileSyncService::ReenableDatatype(syncer::ModelType type
) {
1038 if (!backend_initialized_
)
1040 directory_data_type_manager_
->ReenableType(type
);
1043 void ProfileSyncService::UpdateBackendInitUMA(bool success
) {
1044 if (backend_mode_
!= SYNC
)
1047 is_first_time_sync_configure_
= !HasSyncSetupCompleted();
1049 if (is_first_time_sync_configure_
) {
1050 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success
);
1052 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success
);
1055 base::Time on_backend_initialized_time
= base::Time::Now();
1056 base::TimeDelta delta
= on_backend_initialized_time
-
1057 startup_controller_
->start_backend_time();
1058 if (is_first_time_sync_configure_
) {
1059 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta
);
1061 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta
);
1065 void ProfileSyncService::PostBackendInitialization() {
1066 // Never get here for backup / restore.
1067 DCHECK_EQ(backend_mode_
, SYNC
);
1069 if (last_backup_time_
) {
1070 DCHECK(device_info_sync_service_
);
1071 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
1074 if (protocol_event_observers_
.might_have_observers()) {
1075 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
1078 non_blocking_data_type_manager_
.ConnectSyncBackend(
1079 backend_
->GetSyncContextProxy());
1081 if (type_debug_info_observers_
.might_have_observers()) {
1082 backend_
->EnableDirectoryTypeDebugInfoForwarding();
1085 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1086 // backend is initialized. We want to call this before notifying observers in
1087 // case this operation affects the "passphrase required" status.
1088 ConsumeCachedPassphraseIfPossible();
1090 // The very first time the backend initializes is effectively the first time
1091 // we can say we successfully "synced". LastSyncedTime will only be null in
1092 // this case, because the pref wasn't restored on StartUp.
1093 if (sync_prefs_
.GetLastSyncedTime().is_null()) {
1094 UpdateLastSyncedTime();
1097 if (startup_controller_
->auto_start_enabled() && !FirstSetupInProgress()) {
1098 // Backend is initialized but we're not in sync setup, so this must be an
1099 // autostart - mark our sync setup as completed and we'll start syncing
1101 SetSyncSetupCompleted();
1104 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1105 // data type configuration because observer may flag setup as complete and
1106 // trigger data type configuration.
1107 if (HasSyncSetupCompleted()) {
1108 ConfigureDataTypeManager();
1110 DCHECK(FirstSetupInProgress());
1116 void ProfileSyncService::OnBackendInitialized(
1117 const syncer::WeakHandle
<syncer::JsBackend
>& js_backend
,
1118 const syncer::WeakHandle
<syncer::DataTypeDebugInfoListener
>&
1119 debug_info_listener
,
1120 const std::string
& cache_guid
,
1122 UpdateBackendInitUMA(success
);
1125 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1126 // and surface error UI to alert the user sync has stopped.
1127 // Keep the directory around for now so that on restart we will retry
1128 // again and potentially succeed in presence of transient file IO failures
1129 // or permissions issues, etc.
1131 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1132 // Unlike every other UnrecoverableError, it does not delete our sync data.
1133 // This exception made sense at the time it was implemented, but our new
1134 // directory corruption recovery mechanism makes it obsolete. By the time
1135 // we get here, we will have already tried and failed to delete the
1136 // directory. It would be no big deal if we tried to delete it again.
1137 OnInternalUnrecoverableError(FROM_HERE
,
1138 "BackendInitialize failure",
1140 ERROR_REASON_BACKEND_INIT_FAILURE
);
1144 backend_initialized_
= true;
1146 sync_js_controller_
.AttachJsBackend(js_backend
);
1147 debug_info_listener_
= debug_info_listener
;
1149 SigninClient
* signin_client
=
1150 ChromeSigninClientFactory::GetForProfile(profile_
);
1151 DCHECK(signin_client
);
1152 std::string signin_scoped_device_id
=
1153 signin_client
->GetSigninScopedDeviceId();
1155 // Initialize local device info.
1156 local_device_
->Initialize(cache_guid
, signin_scoped_device_id
);
1158 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1159 non_blocking_data_type_manager_
.SetPreferredTypes(GetPreferredDataTypes());
1161 // Give the DataTypeControllers a handle to the now initialized backend
1163 for (DataTypeController::TypeMap::iterator it
=
1164 directory_data_type_controllers_
.begin();
1165 it
!= directory_data_type_controllers_
.end(); ++it
) {
1166 it
->second
->OnUserShareReady(GetUserShare());
1169 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
)
1170 ConfigureDataTypeManager();
1172 PostBackendInitialization();
1175 void ProfileSyncService::OnSyncCycleCompleted() {
1176 UpdateLastSyncedTime();
1177 if (IsDataTypeControllerRunning(syncer::SESSIONS
)) {
1178 // Trigger garbage collection of old sessions now that we've downloaded
1179 // any new session data.
1180 base::ThreadTaskRunnerHandle::Get()->PostTask(
1181 FROM_HERE
, base::Bind(&SessionsSyncManager::DoGarbageCollection
,
1182 base::AsWeakPtr(sessions_sync_manager_
.get())));
1184 DVLOG(2) << "Notifying observers sync cycle completed";
1185 NotifySyncCycleCompleted();
1188 void ProfileSyncService::OnExperimentsChanged(
1189 const syncer::Experiments
& experiments
) {
1190 if (current_experiments_
.Matches(experiments
))
1193 current_experiments_
= experiments
;
1195 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel
,
1196 experiments
.gcm_invalidations_enabled
);
1197 profile()->GetPrefs()->SetBoolean(
1198 autofill::prefs::kAutofillWalletSyncExperimentEnabled
,
1199 experiments
.wallet_sync_enabled
);
1202 void ProfileSyncService::UpdateAuthErrorState(const AuthError
& error
) {
1203 is_auth_in_progress_
= false;
1204 last_auth_error_
= error
;
1211 AuthError
ConnectionStatusToAuthError(
1212 syncer::ConnectionStatus status
) {
1214 case syncer::CONNECTION_OK
:
1215 return AuthError::AuthErrorNone();
1217 case syncer::CONNECTION_AUTH_ERROR
:
1218 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS
);
1220 case syncer::CONNECTION_SERVER_ERROR
:
1221 return AuthError(AuthError::CONNECTION_FAILED
);
1225 return AuthError(AuthError::CONNECTION_FAILED
);
1231 void ProfileSyncService::OnConnectionStatusChange(
1232 syncer::ConnectionStatus status
) {
1233 connection_status_update_time_
= base::Time::Now();
1234 connection_status_
= status
;
1235 if (status
== syncer::CONNECTION_AUTH_ERROR
) {
1236 // Sync server returned error indicating that access token is invalid. It
1237 // could be either expired or access is revoked. Let's request another
1238 // access token and if access is revoked then request for token will fail
1239 // with corresponding error. If access token is repeatedly reported
1240 // invalid, there may be some issues with server, e.g. authentication
1241 // state is inconsistent on sync and token server. In that case, we
1242 // backoff token requests exponentially to avoid hammering token server
1243 // too much and to avoid getting same token due to token server's caching
1244 // policy. |request_access_token_retry_timer_| is used to backoff request
1245 // triggered by both auth error and failure talking to GAIA server.
1246 // Therefore, we're likely to reach the backoff ceiling more quickly than
1247 // you would expect from looking at the BackoffPolicy if both types of
1248 // errors happen. We shouldn't receive two errors back-to-back without
1249 // attempting a token/sync request in between, thus crank up request delay
1250 // unnecessary. This is because we won't make a sync request if we hit an
1251 // error until GAIA succeeds at sending a new token, and we won't request
1252 // a new token unless sync reports a token failure. But to be safe, don't
1253 // schedule request if this happens.
1254 if (request_access_token_retry_timer_
.IsRunning()) {
1255 // The timer to perform a request later is already running; nothing
1256 // further needs to be done at this point.
1257 } else if (request_access_token_backoff_
.failure_count() == 0) {
1258 // First time request without delay. Currently invalid token is used
1259 // to initialize sync backend and we'll always end up here. We don't
1260 // want to delay initialization.
1261 request_access_token_backoff_
.InformOfRequest(false);
1262 RequestAccessToken();
1264 request_access_token_backoff_
.InformOfRequest(false);
1265 request_access_token_retry_timer_
.Start(
1267 request_access_token_backoff_
.GetTimeUntilRelease(),
1268 base::Bind(&ProfileSyncService::RequestAccessToken
,
1269 weak_factory_
.GetWeakPtr()));
1272 // Reset backoff time after successful connection.
1273 if (status
== syncer::CONNECTION_OK
) {
1274 // Request shouldn't be scheduled at this time. But if it is, it's
1275 // possible that sync flips between OK and auth error states rapidly,
1276 // thus hammers token server. To be safe, only reset backoff delay when
1277 // no scheduled request.
1278 if (request_access_token_retry_timer_
.IsRunning()) {
1281 request_access_token_backoff_
.Reset();
1285 const GoogleServiceAuthError auth_error
=
1286 ConnectionStatusToAuthError(status
);
1287 DVLOG(1) << "Connection status change: " << auth_error
.ToString();
1288 UpdateAuthErrorState(auth_error
);
1292 void ProfileSyncService::OnPassphraseRequired(
1293 syncer::PassphraseRequiredReason reason
,
1294 const sync_pb::EncryptedData
& pending_keys
) {
1295 DCHECK(backend_
.get());
1296 DCHECK(backend_
->IsNigoriEnabled());
1298 // TODO(lipalani) : add this check to other locations as well.
1299 if (HasUnrecoverableError()) {
1300 // When unrecoverable error is detected we post a task to shutdown the
1301 // backend. The task might not have executed yet.
1305 DVLOG(1) << "Passphrase required with reason: "
1306 << syncer::PassphraseRequiredReasonToString(reason
);
1307 passphrase_required_reason_
= reason
;
1309 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1310 if (directory_data_type_manager_
) {
1311 // Reconfigure without the encrypted types (excluded implicitly via the
1312 // failed datatypes handler).
1313 directory_data_type_manager_
->Configure(types
,
1314 syncer::CONFIGURE_REASON_CRYPTO
);
1317 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1319 // Notify observers that the passphrase status may have changed.
1323 void ProfileSyncService::OnPassphraseAccepted() {
1324 DVLOG(1) << "Received OnPassphraseAccepted.";
1326 // If the pending keys were resolved via keystore, it's possible we never
1327 // consumed our cached passphrase. Clear it now.
1328 if (!cached_passphrase_
.empty())
1329 cached_passphrase_
.clear();
1331 // Reset passphrase_required_reason_ since we know we no longer require the
1332 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1333 // because that can be called by OnPassphraseRequired() if no encrypted data
1334 // types are enabled, and we don't want to clobber the true passphrase error.
1335 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1337 // Make sure the data types that depend on the passphrase are started at
1339 const syncer::ModelTypeSet types
= GetPreferredDirectoryDataTypes();
1340 if (directory_data_type_manager_
) {
1341 // Re-enable any encrypted types if necessary.
1342 directory_data_type_manager_
->Configure(types
,
1343 syncer::CONFIGURE_REASON_CRYPTO
);
1346 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1351 void ProfileSyncService::OnEncryptedTypesChanged(
1352 syncer::ModelTypeSet encrypted_types
,
1353 bool encrypt_everything
) {
1354 encrypted_types_
= encrypted_types
;
1355 encrypt_everything_
= encrypt_everything
;
1356 DCHECK(encrypt_everything_allowed_
|| !encrypt_everything_
);
1357 DVLOG(1) << "Encrypted types changed to "
1358 << syncer::ModelTypeSetToString(encrypted_types_
)
1359 << " (encrypt everything is set to "
1360 << (encrypt_everything_
? "true" : "false") << ")";
1361 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
1366 void ProfileSyncService::OnEncryptionComplete() {
1367 DVLOG(1) << "Encryption complete";
1368 if (encryption_pending_
&& encrypt_everything_
) {
1369 encryption_pending_
= false;
1370 // This is to nudge the integration tests when encryption is
1376 void ProfileSyncService::OnMigrationNeededForTypes(
1377 syncer::ModelTypeSet types
) {
1378 DCHECK(backend_initialized_
);
1379 DCHECK(directory_data_type_manager_
.get());
1381 // Migrator must be valid, because we don't sync until it is created and this
1382 // callback originates from a sync cycle.
1383 migrator_
->MigrateTypes(types
);
1386 void ProfileSyncService::OnActionableError(const SyncProtocolError
& error
) {
1387 last_actionable_error_
= error
;
1388 DCHECK_NE(last_actionable_error_
.action
,
1389 syncer::UNKNOWN_ACTION
);
1390 switch (error
.action
) {
1391 case syncer::UPGRADE_CLIENT
:
1392 case syncer::CLEAR_USER_DATA_AND_RESYNC
:
1393 case syncer::ENABLE_SYNC_ON_ACCOUNT
:
1394 case syncer::STOP_AND_RESTART_SYNC
:
1395 // TODO(lipalani) : if setup in progress we want to display these
1396 // actions in the popup. The current experience might not be optimal for
1397 // the user. We just dismiss the dialog.
1398 if (startup_controller_
->setup_in_progress()) {
1399 RequestStop(CLEAR_DATA
);
1400 expect_sync_configuration_aborted_
= true;
1402 // Trigger an unrecoverable error to stop syncing.
1403 OnInternalUnrecoverableError(FROM_HERE
,
1404 last_actionable_error_
.error_description
,
1406 ERROR_REASON_ACTIONABLE_ERROR
);
1408 case syncer::DISABLE_SYNC_AND_ROLLBACK
:
1409 backup_rollback_controller_
->OnRollbackReceived();
1410 // Fall through to shutdown backend and sign user out.
1411 case syncer::DISABLE_SYNC_ON_CLIENT
:
1412 RequestStop(CLEAR_DATA
);
1413 #if !defined(OS_CHROMEOS)
1414 // On desktop Chrome, sign out the user after a dashboard clear.
1415 // Skip sign out on ChromeOS/Android.
1416 if (!startup_controller_
->auto_start_enabled()) {
1417 SigninManagerFactory::GetForProfile(profile_
)->SignOut(
1418 signin_metrics::SERVER_FORCED_DISABLE
);
1422 case syncer::ROLLBACK_DONE
:
1423 backup_rollback_controller_
->OnRollbackDone();
1425 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT
:
1426 // Sync disabled by domain admin. we should stop syncing until next
1428 sync_disabled_by_admin_
= true;
1429 ShutdownImpl(syncer::DISABLE_SYNC
);
1436 if (error
.action
== syncer::DISABLE_SYNC_ON_CLIENT
||
1437 (error
.action
== syncer::DISABLE_SYNC_AND_ROLLBACK
&&
1438 !backup_rollback_controller_
->StartRollback())) {
1439 // Clean up backup data for sign-out only or when rollback is disabled.
1441 } else if (error
.action
== syncer::ROLLBACK_DONE
) {
1442 // Shut down ROLLBACK backend and delete backup DB.
1443 ShutdownImpl(syncer::DISABLE_SYNC
);
1444 sync_prefs_
.ClearFirstSyncTime();
1448 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1449 const syncer::SyncEncryptionHandler::NigoriState
& nigori_state
) {
1450 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1451 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1452 switches::kSyncEnableClearDataOnPassphraseEncryption
))
1455 // At this point the user has set a custom passphrase and we have received the
1456 // updated nigori state. Time to cache the nigori state, and catch up the
1457 // active data types.
1458 sync_prefs_
.SetSavedNigoriStateForPassphraseEncryptionTransition(
1460 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(true);
1461 BeginConfigureCatchUpBeforeClear();
1464 void ProfileSyncService::BeginConfigureCatchUpBeforeClear() {
1465 DCHECK_EQ(backend_mode_
, SYNC
);
1466 DCHECK(directory_data_type_manager_
);
1467 DCHECK(!saved_nigori_state_
);
1468 saved_nigori_state_
=
1469 sync_prefs_
.GetSavedNigoriStateForPassphraseEncryptionTransition().Pass();
1470 const syncer::ModelTypeSet types
= GetActiveDataTypes();
1471 catch_up_configure_in_progress_
= true;
1472 directory_data_type_manager_
->Configure(types
,
1473 syncer::CONFIGURE_REASON_CATCH_UP
);
1476 void ProfileSyncService::ClearAndRestartSyncForPassphraseEncryption() {
1477 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
1478 backend_
->ClearServerData(base::Bind(
1479 &ProfileSyncService::OnClearServerDataDone
, weak_factory_
.GetWeakPtr()));
1482 void ProfileSyncService::OnClearServerDataDone() {
1483 DCHECK(sync_prefs_
.GetPassphraseEncryptionTransitionInProgress());
1484 sync_prefs_
.SetPassphraseEncryptionTransitionInProgress(false);
1486 // Call to ClearServerData generates new keystore key on the server. This
1487 // makes keystore bootstrap token invalid. Let's clear it from preferences.
1488 sync_prefs_
.SetKeystoreEncryptionBootstrapToken(std::string());
1490 // Shutdown sync, delete the Directory, then restart, restoring the cached
1492 ShutdownImpl(syncer::DISABLE_SYNC
);
1493 startup_controller_
->TryStart();
1496 void ProfileSyncService::OnConfigureDone(
1497 const DataTypeManager::ConfigureResult
& result
) {
1498 configure_status_
= result
.status
;
1499 data_type_status_table_
= result
.data_type_status_table
;
1501 if (backend_mode_
!= SYNC
) {
1502 if (configure_status_
== DataTypeManager::OK
) {
1503 StartSyncingWithServer();
1505 // Backup is done after models are associated.
1506 if (backend_mode_
== BACKUP
)
1507 backup_finished_
= true;
1509 // Asynchronously check whether sync needs to start.
1510 base::ThreadTaskRunnerHandle::Get()->PostTask(
1511 FROM_HERE
, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup
,
1512 startup_controller_weak_factory_
.GetWeakPtr()));
1513 } else if (!expect_sync_configuration_aborted_
) {
1514 DVLOG(1) << "Backup/rollback backend failed to configure.";
1515 ShutdownImpl(syncer::STOP_SYNC
);
1521 // We should have cleared our cached passphrase before we get here (in
1522 // OnBackendInitialized()).
1523 DCHECK(cached_passphrase_
.empty());
1525 if (!sync_configure_start_time_
.is_null()) {
1526 if (result
.status
== DataTypeManager::OK
) {
1527 base::Time sync_configure_stop_time
= base::Time::Now();
1528 base::TimeDelta delta
= sync_configure_stop_time
-
1529 sync_configure_start_time_
;
1530 if (is_first_time_sync_configure_
) {
1531 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta
);
1533 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1537 sync_configure_start_time_
= base::Time();
1540 // Notify listeners that configuration is done.
1541 content::NotificationService::current()->Notify(
1542 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE
,
1543 content::Source
<ProfileSyncService
>(this),
1544 content::NotificationService::NoDetails());
1546 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_
;
1547 // The possible status values:
1548 // ABORT - Configuration was aborted. This is not an error, if
1549 // initiated by user.
1550 // OK - Some or all types succeeded.
1551 // Everything else is an UnrecoverableError. So treat it as such.
1553 // First handle the abort case.
1554 if (configure_status_
== DataTypeManager::ABORTED
&&
1555 expect_sync_configuration_aborted_
) {
1556 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1557 expect_sync_configuration_aborted_
= false;
1561 // Handle unrecoverable error.
1562 if (configure_status_
!= DataTypeManager::OK
) {
1563 // Something catastrophic had happened. We should only have one
1564 // error representing it.
1565 syncer::SyncError error
=
1566 data_type_status_table_
.GetUnrecoverableError();
1567 DCHECK(error
.IsSet());
1568 std::string message
=
1569 "Sync configuration failed with status " +
1570 DataTypeManager::ConfigureStatusToString(configure_status_
) +
1572 syncer::ModelTypeSetToString(
1573 data_type_status_table_
.GetUnrecoverableErrorTypes()) +
1574 ": " + error
.message();
1575 LOG(ERROR
) << "ProfileSyncService error: " << message
;
1576 OnInternalUnrecoverableError(error
.location(),
1579 ERROR_REASON_CONFIGURATION_FAILURE
);
1583 DCHECK_EQ(DataTypeManager::OK
, configure_status_
);
1585 // We should never get in a state where we have no encrypted datatypes
1586 // enabled, and yet we still think we require a passphrase for decryption.
1587 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1588 !IsEncryptedDatatypeEnabled()));
1590 // This must be done before we start syncing with the server to avoid
1591 // sending unencrypted data up on a first time sync.
1592 if (encryption_pending_
)
1593 backend_
->EnableEncryptEverything();
1596 if (migrator_
.get() &&
1597 migrator_
->state() != browser_sync::BackendMigrator::IDLE
) {
1598 // Migration in progress. Let the migrator know we just finished
1599 // configuring something. It will be up to the migrator to call
1600 // StartSyncingWithServer() if migration is now finished.
1601 migrator_
->OnConfigureDone(result
);
1605 if (catch_up_configure_in_progress_
) {
1606 catch_up_configure_in_progress_
= false;
1607 ClearAndRestartSyncForPassphraseEncryption();
1611 StartSyncingWithServer();
1614 void ProfileSyncService::OnConfigureStart() {
1615 sync_configure_start_time_
= base::Time::Now();
1619 ProfileSyncService::SyncStatusSummary
1620 ProfileSyncService::QuerySyncStatusSummary() {
1621 if (HasUnrecoverableError()) {
1622 return UNRECOVERABLE_ERROR
;
1623 } else if (!backend_
) {
1625 } else if (backend_mode_
== BACKUP
) {
1626 return BACKUP_USER_DATA
;
1627 } else if (backend_mode_
== ROLLBACK
) {
1628 return ROLLBACK_USER_DATA
;
1629 } else if (backend_
.get() && !HasSyncSetupCompleted()) {
1630 return SETUP_INCOMPLETE
;
1632 backend_
.get() && HasSyncSetupCompleted() &&
1633 directory_data_type_manager_
.get() &&
1634 directory_data_type_manager_
->state() == DataTypeManager::STOPPED
) {
1635 return DATATYPES_NOT_INITIALIZED
;
1636 } else if (IsSyncActive()) {
1639 return UNKNOWN_ERROR
;
1642 std::string
ProfileSyncService::QuerySyncStatusSummaryString() {
1643 SyncStatusSummary status
= QuerySyncStatusSummary();
1645 std::string config_status_str
=
1646 configure_status_
!= DataTypeManager::UNKNOWN
?
1647 DataTypeManager::ConfigureStatusToString(configure_status_
) : "";
1650 case UNRECOVERABLE_ERROR
:
1651 return "Unrecoverable error detected";
1653 return "Syncing not enabled";
1654 case SETUP_INCOMPLETE
:
1655 return "First time sync setup incomplete";
1656 case DATATYPES_NOT_INITIALIZED
:
1657 return "Datatypes not fully initialized";
1659 return "Sync service initialized";
1660 case BACKUP_USER_DATA
:
1661 return "Backing-up user data. Status: " + config_status_str
;
1662 case ROLLBACK_USER_DATA
:
1663 return "Restoring user data. Status: " + config_status_str
;
1665 return "Status unknown: Internal error?";
1669 std::string
ProfileSyncService::GetBackendInitializationStateString() const {
1670 return startup_controller_
->GetBackendInitializationStateString();
1673 bool ProfileSyncService::auto_start_enabled() const {
1674 return startup_controller_
->auto_start_enabled();
1677 bool ProfileSyncService::setup_in_progress() const {
1678 return startup_controller_
->setup_in_progress();
1681 bool ProfileSyncService::QueryDetailedSyncStatus(
1682 SyncBackendHost::Status
* result
) {
1683 if (backend_
.get() && backend_initialized_
) {
1684 *result
= backend_
->GetDetailedStatus();
1687 SyncBackendHost::Status status
;
1688 status
.sync_protocol_error
= last_actionable_error_
;
1694 const AuthError
& ProfileSyncService::GetAuthError() const {
1695 return last_auth_error_
;
1698 bool ProfileSyncService::FirstSetupInProgress() const {
1699 return !HasSyncSetupCompleted() && startup_controller_
->setup_in_progress();
1702 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress
) {
1703 // This method is a no-op if |setup_in_progress_| remains unchanged.
1704 if (startup_controller_
->setup_in_progress() == setup_in_progress
)
1707 startup_controller_
->set_setup_in_progress(setup_in_progress
);
1708 if (!setup_in_progress
&& backend_initialized())
1709 ReconfigureDatatypeManager();
1713 bool ProfileSyncService::IsSyncAllowed() const {
1714 return IsSyncAllowedByFlag() && !IsManaged();
1717 bool ProfileSyncService::IsSyncActive() const {
1718 return backend_initialized_
&& backend_mode_
== SYNC
&&
1719 directory_data_type_manager_
&&
1720 directory_data_type_manager_
->state() != DataTypeManager::STOPPED
;
1723 bool ProfileSyncService::IsSignedIn() const {
1724 // Sync is logged in if there is a non-empty effective account id.
1725 return !signin_
->GetAccountIdToUse().empty();
1728 bool ProfileSyncService::backend_initialized() const {
1729 return backend_initialized_
;
1732 ProfileSyncService::BackendMode
ProfileSyncService::backend_mode() const {
1733 return backend_mode_
;
1736 bool ProfileSyncService::ConfigurationDone() const {
1737 return directory_data_type_manager_
&&
1738 directory_data_type_manager_
->state() == DataTypeManager::CONFIGURED
;
1741 bool ProfileSyncService::waiting_for_auth() const {
1742 return is_auth_in_progress_
;
1745 const syncer::Experiments
& ProfileSyncService::current_experiments() const {
1746 return current_experiments_
;
1749 bool ProfileSyncService::HasUnrecoverableError() const {
1750 return unrecoverable_error_reason_
!= ERROR_REASON_UNSET
;
1753 bool ProfileSyncService::IsPassphraseRequired() const {
1754 return passphrase_required_reason_
!=
1755 syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
1758 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1759 // If there is an encrypted datatype enabled and we don't have the proper
1760 // passphrase, we must prompt the user for a passphrase. The only way for the
1761 // user to avoid entering their passphrase is to disable the encrypted types.
1762 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1765 base::string16
ProfileSyncService::GetLastSyncedTimeString() const {
1766 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
1767 if (last_synced_time
.is_null())
1768 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
);
1770 base::TimeDelta time_since_last_sync
= base::Time::Now() - last_synced_time
;
1772 if (time_since_last_sync
< base::TimeDelta::FromMinutes(1))
1773 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
);
1775 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED
,
1776 ui::TimeFormat::LENGTH_SHORT
,
1777 time_since_last_sync
);
1780 void ProfileSyncService::UpdateSelectedTypesHistogram(
1781 bool sync_everything
, const syncer::ModelTypeSet chosen_types
) const {
1782 if (!HasSyncSetupCompleted() ||
1783 sync_everything
!= sync_prefs_
.HasKeepEverythingSynced()) {
1784 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything
);
1787 // Only log the data types that are shown in the sync settings ui.
1788 // Note: the order of these types must match the ordering of
1789 // the respective types in ModelType
1790 const sync_driver::user_selectable_type::UserSelectableSyncType
1791 user_selectable_types
[] = {
1792 sync_driver::user_selectable_type::BOOKMARKS
,
1793 sync_driver::user_selectable_type::PREFERENCES
,
1794 sync_driver::user_selectable_type::PASSWORDS
,
1795 sync_driver::user_selectable_type::AUTOFILL
,
1796 sync_driver::user_selectable_type::THEMES
,
1797 sync_driver::user_selectable_type::TYPED_URLS
,
1798 sync_driver::user_selectable_type::EXTENSIONS
,
1799 sync_driver::user_selectable_type::APPS
,
1800 sync_driver::user_selectable_type::WIFI_CREDENTIAL
,
1801 sync_driver::user_selectable_type::PROXY_TABS
,
1804 static_assert(36 == syncer::MODEL_TYPE_COUNT
,
1805 "custom config histogram must be updated");
1807 if (!sync_everything
) {
1808 const syncer::ModelTypeSet current_types
= GetPreferredDataTypes();
1810 syncer::ModelTypeSet type_set
= syncer::UserSelectableTypes();
1811 syncer::ModelTypeSet::Iterator it
= type_set
.First();
1813 DCHECK_EQ(arraysize(user_selectable_types
), type_set
.Size());
1815 for (size_t i
= 0; i
< arraysize(user_selectable_types
) && it
.Good();
1817 const syncer::ModelType type
= it
.Get();
1818 if (chosen_types
.Has(type
) &&
1819 (!HasSyncSetupCompleted() || !current_types
.Has(type
))) {
1820 // Selected type has changed - log it.
1821 UMA_HISTOGRAM_ENUMERATION(
1823 user_selectable_types
[i
],
1824 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT
+ 1);
1830 #if defined(OS_CHROMEOS)
1831 void ProfileSyncService::RefreshSpareBootstrapToken(
1832 const std::string
& passphrase
) {
1833 sync_driver::SystemEncryptor encryptor
;
1834 syncer::Cryptographer
temp_cryptographer(&encryptor
);
1835 // The first 2 params (hostname and username) doesn't have any effect here.
1836 syncer::KeyParams key_params
= {"localhost", "dummy", passphrase
};
1838 std::string bootstrap_token
;
1839 if (!temp_cryptographer
.AddKey(key_params
)) {
1840 NOTREACHED() << "Failed to add key to cryptographer.";
1842 temp_cryptographer
.GetBootstrapToken(&bootstrap_token
);
1843 sync_prefs_
.SetSpareBootstrapToken(bootstrap_token
);
1847 void ProfileSyncService::OnUserChoseDatatypes(
1848 bool sync_everything
,
1849 syncer::ModelTypeSet chosen_types
) {
1850 if (!backend_
.get() && !HasUnrecoverableError()) {
1855 UpdateSelectedTypesHistogram(sync_everything
, chosen_types
);
1856 sync_prefs_
.SetKeepEverythingSynced(sync_everything
);
1858 if (directory_data_type_manager_
.get())
1859 directory_data_type_manager_
->ResetDataTypeErrors();
1860 ChangePreferredDataTypes(chosen_types
);
1863 void ProfileSyncService::ChangePreferredDataTypes(
1864 syncer::ModelTypeSet preferred_types
) {
1866 DVLOG(1) << "ChangePreferredDataTypes invoked";
1867 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1868 // Will only enable those types that are registered and preferred.
1869 sync_prefs_
.SetPreferredDataTypes(registered_types
, preferred_types
);
1871 // Now reconfigure the DTM.
1872 ReconfigureDatatypeManager();
1874 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1875 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1876 // which types should be enabled and when.
1879 syncer::ModelTypeSet
ProfileSyncService::GetActiveDataTypes() const {
1880 if (!IsSyncActive() || !ConfigurationDone())
1881 return syncer::ModelTypeSet();
1882 const syncer::ModelTypeSet preferred_types
= GetPreferredDataTypes();
1883 const syncer::ModelTypeSet failed_types
=
1884 data_type_status_table_
.GetFailedTypes();
1885 return Difference(preferred_types
, failed_types
);
1888 syncer::ModelTypeSet
ProfileSyncService::GetPreferredDataTypes() const {
1889 const syncer::ModelTypeSet registered_types
= GetRegisteredDataTypes();
1890 const syncer::ModelTypeSet preferred_types
=
1891 sync_prefs_
.GetPreferredDataTypes(registered_types
);
1892 const syncer::ModelTypeSet enforced_types
=
1893 Intersection(GetDataTypesFromPreferenceProviders(), registered_types
);
1894 return Union(preferred_types
, enforced_types
);
1897 syncer::ModelTypeSet
1898 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1899 const syncer::ModelTypeSet registered_directory_types
=
1900 GetRegisteredDirectoryDataTypes();
1901 const syncer::ModelTypeSet preferred_types
=
1902 sync_prefs_
.GetPreferredDataTypes(registered_directory_types
);
1903 const syncer::ModelTypeSet enforced_types
=
1904 Intersection(GetDataTypesFromPreferenceProviders(),
1905 registered_directory_types
);
1906 return Union(preferred_types
, enforced_types
);
1909 syncer::ModelTypeSet
1910 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1911 return sync_prefs_
.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1914 syncer::ModelTypeSet
ProfileSyncService::GetForcedDataTypes() const {
1915 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1916 // we'll need another way to distinguish user-choosable types from
1917 // programmatically-enabled types.
1918 return GetDataTypesFromPreferenceProviders();
1921 syncer::ModelTypeSet
ProfileSyncService::GetRegisteredDataTypes() const {
1922 return Union(GetRegisteredDirectoryDataTypes(),
1923 GetRegisteredNonBlockingDataTypes());
1926 syncer::ModelTypeSet
1927 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1928 syncer::ModelTypeSet registered_types
;
1929 // The directory_data_type_controllers_ are determined by command-line flags;
1930 // that's effectively what controls the values returned here.
1931 for (DataTypeController::TypeMap::const_iterator it
=
1932 directory_data_type_controllers_
.begin();
1933 it
!= directory_data_type_controllers_
.end(); ++it
) {
1934 registered_types
.Put(it
->first
);
1936 return registered_types
;
1939 syncer::ModelTypeSet
1940 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1941 return non_blocking_data_type_manager_
.GetRegisteredTypes();
1944 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1945 syncer::PassphraseType passphrase_type
= GetPassphraseType();
1946 return passphrase_type
== syncer::FROZEN_IMPLICIT_PASSPHRASE
||
1947 passphrase_type
== syncer::CUSTOM_PASSPHRASE
;
1950 syncer::PassphraseType
ProfileSyncService::GetPassphraseType() const {
1951 return backend_
->GetPassphraseType();
1954 base::Time
ProfileSyncService::GetExplicitPassphraseTime() const {
1955 return backend_
->GetExplicitPassphraseTime();
1958 bool ProfileSyncService::IsCryptographerReady(
1959 const syncer::BaseTransaction
* trans
) const {
1960 return backend_
.get() && backend_
->IsCryptographerReady(trans
);
1963 void ProfileSyncService::ConfigureDataTypeManager() {
1964 // Don't configure datatypes if the setup UI is still on the screen - this
1965 // is to help multi-screen setting UIs (like iOS) where they don't want to
1966 // start syncing data until the user is done configuring encryption options,
1967 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1968 // SetSetupInProgress(false).
1969 if (backend_mode_
== SYNC
&& startup_controller_
->setup_in_progress())
1972 bool restart
= false;
1973 if (!directory_data_type_manager_
) {
1975 directory_data_type_manager_
.reset(
1976 factory_
->CreateDataTypeManager(debug_info_listener_
,
1977 &directory_data_type_controllers_
,
1982 // We create the migrator at the same time.
1984 new browser_sync::BackendMigrator(
1985 profile_
->GetDebugName(), GetUserShare(),
1986 this, directory_data_type_manager_
.get(),
1987 base::Bind(&ProfileSyncService::StartSyncingWithServer
,
1988 base::Unretained(this))));
1991 syncer::ModelTypeSet types
;
1992 syncer::ConfigureReason reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
1993 if (backend_mode_
== BACKUP
|| backend_mode_
== ROLLBACK
) {
1994 types
= syncer::BackupTypes();
1995 reason
= syncer::CONFIGURE_REASON_BACKUP_ROLLBACK
;
1997 types
= GetPreferredDirectoryDataTypes();
1998 if (!HasSyncSetupCompleted()) {
1999 reason
= syncer::CONFIGURE_REASON_NEW_CLIENT
;
2000 } else if (restart
) {
2001 // Datatype downloads on restart are generally due to newly supported
2002 // datatypes (although it's also possible we're picking up where a failed
2003 // previous configuration left off).
2004 // TODO(sync): consider detecting configuration recovery and setting
2005 // the reason here appropriately.
2006 reason
= syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
;
2008 // The user initiated a reconfiguration (either to add or remove types).
2009 reason
= syncer::CONFIGURE_REASON_RECONFIGURATION
;
2013 directory_data_type_manager_
->Configure(types
, reason
);
2016 syncer::UserShare
* ProfileSyncService::GetUserShare() const {
2017 if (backend_
.get() && backend_initialized_
) {
2018 return backend_
->GetUserShare();
2024 syncer::sessions::SyncSessionSnapshot
2025 ProfileSyncService::GetLastSessionSnapshot() const {
2027 return backend_
->GetLastSessionSnapshot();
2028 return syncer::sessions::SyncSessionSnapshot();
2031 bool ProfileSyncService::HasUnsyncedItems() const {
2032 if (HasSyncingBackend() && backend_initialized_
) {
2033 return backend_
->HasUnsyncedItems();
2039 browser_sync::BackendMigrator
*
2040 ProfileSyncService::GetBackendMigratorForTest() {
2041 return migrator_
.get();
2044 void ProfileSyncService::GetModelSafeRoutingInfo(
2045 syncer::ModelSafeRoutingInfo
* out
) const {
2046 if (backend_
.get() && backend_initialized_
) {
2047 backend_
->GetModelSafeRoutingInfo(out
);
2053 base::Value
* ProfileSyncService::GetTypeStatusMap() const {
2054 scoped_ptr
<base::ListValue
> result(new base::ListValue());
2056 if (!backend_
.get() || !backend_initialized_
) {
2057 return result
.release();
2060 DataTypeStatusTable::TypeErrorMap error_map
=
2061 data_type_status_table_
.GetAllErrors();
2062 ModelTypeSet active_types
;
2063 ModelTypeSet passive_types
;
2064 ModelSafeRoutingInfo routing_info
;
2065 backend_
->GetModelSafeRoutingInfo(&routing_info
);
2066 for (ModelSafeRoutingInfo::const_iterator it
= routing_info
.begin();
2067 it
!= routing_info
.end(); ++it
) {
2068 if (it
->second
== syncer::GROUP_PASSIVE
) {
2069 passive_types
.Put(it
->first
);
2071 active_types
.Put(it
->first
);
2075 SyncBackendHost::Status detailed_status
= backend_
->GetDetailedStatus();
2076 ModelTypeSet
&throttled_types(detailed_status
.throttled_types
);
2077 ModelTypeSet registered
= GetRegisteredDataTypes();
2078 scoped_ptr
<base::DictionaryValue
> type_status_header(
2079 new base::DictionaryValue());
2081 type_status_header
->SetString("name", "Model Type");
2082 type_status_header
->SetString("status", "header");
2083 type_status_header
->SetString("value", "Group Type");
2084 type_status_header
->SetString("num_entries", "Total Entries");
2085 type_status_header
->SetString("num_live", "Live Entries");
2086 result
->Append(type_status_header
.release());
2088 scoped_ptr
<base::DictionaryValue
> type_status
;
2089 for (ModelTypeSet::Iterator it
= registered
.First(); it
.Good(); it
.Inc()) {
2090 ModelType type
= it
.Get();
2092 type_status
.reset(new base::DictionaryValue());
2093 type_status
->SetString("name", ModelTypeToString(type
));
2095 if (error_map
.find(type
) != error_map
.end()) {
2096 const syncer::SyncError
&error
= error_map
.find(type
)->second
;
2097 DCHECK(error
.IsSet());
2098 switch (error
.GetSeverity()) {
2099 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR
: {
2100 std::string error_text
= "Error: " + error
.location().ToString() +
2101 ", " + error
.GetMessagePrefix() + error
.message();
2102 type_status
->SetString("status", "error");
2103 type_status
->SetString("value", error_text
);
2106 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO
:
2107 type_status
->SetString("status", "disabled");
2108 type_status
->SetString("value", error
.message());
2111 NOTREACHED() << "Unexpected error severity.";
2114 } else if (syncer::IsProxyType(type
) && passive_types
.Has(type
)) {
2115 // Show a proxy type in "ok" state unless it is disabled by user.
2116 DCHECK(!throttled_types
.Has(type
));
2117 type_status
->SetString("status", "ok");
2118 type_status
->SetString("value", "Passive");
2119 } else if (throttled_types
.Has(type
) && passive_types
.Has(type
)) {
2120 type_status
->SetString("status", "warning");
2121 type_status
->SetString("value", "Passive, Throttled");
2122 } else if (passive_types
.Has(type
)) {
2123 type_status
->SetString("status", "warning");
2124 type_status
->SetString("value", "Passive");
2125 } else if (throttled_types
.Has(type
)) {
2126 type_status
->SetString("status", "warning");
2127 type_status
->SetString("value", "Throttled");
2128 } else if (GetRegisteredNonBlockingDataTypes().Has(type
)) {
2129 type_status
->SetString("status", "ok");
2130 type_status
->SetString("value", "Non-Blocking");
2131 } else if (active_types
.Has(type
)) {
2132 type_status
->SetString("status", "ok");
2133 type_status
->SetString("value", "Active: " +
2134 ModelSafeGroupToString(routing_info
[type
]));
2136 type_status
->SetString("status", "warning");
2137 type_status
->SetString("value", "Disabled by User");
2140 int live_count
= detailed_status
.num_entries_by_type
[type
] -
2141 detailed_status
.num_to_delete_entries_by_type
[type
];
2142 type_status
->SetInteger("num_entries",
2143 detailed_status
.num_entries_by_type
[type
]);
2144 type_status
->SetInteger("num_live", live_count
);
2146 result
->Append(type_status
.release());
2148 return result
.release();
2151 void ProfileSyncService::DeactivateDataType(syncer::ModelType type
) {
2154 backend_
->DeactivateDataType(type
);
2157 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2158 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2159 // If the backend isn't running yet, OnBackendInitialized() will call this
2160 // method again after the backend starts up.
2161 if (cached_passphrase_
.empty() || !backend_initialized())
2164 // Backend is up and running, so we can consume the cached passphrase.
2165 std::string passphrase
= cached_passphrase_
;
2166 cached_passphrase_
.clear();
2168 // If we need a passphrase to decrypt data, try the cached passphrase.
2169 if (passphrase_required_reason() == syncer::REASON_DECRYPTION
) {
2170 if (SetDecryptionPassphrase(passphrase
)) {
2171 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2176 // If we get here, we don't have pending keys (or at least, the passphrase
2177 // doesn't decrypt them) - just try to re-encrypt using the encryption
2179 if (!IsUsingSecondaryPassphrase())
2180 SetEncryptionPassphrase(passphrase
, IMPLICIT
);
2183 void ProfileSyncService::RequestAccessToken() {
2184 // Only one active request at a time.
2185 if (access_token_request_
!= NULL
)
2187 request_access_token_retry_timer_
.Stop();
2188 OAuth2TokenService::ScopeSet oauth2_scopes
;
2189 oauth2_scopes
.insert(signin_
->GetSyncScopeToUse());
2191 // Invalidate previous token, otherwise token service will return the same
2193 const std::string
& account_id
= signin_
->GetAccountIdToUse();
2194 if (!access_token_
.empty()) {
2195 oauth2_token_service_
->InvalidateAccessToken(account_id
, oauth2_scopes
,
2199 access_token_
.clear();
2201 token_request_time_
= base::Time::Now();
2202 token_receive_time_
= base::Time();
2203 next_token_request_time_
= base::Time();
2204 access_token_request_
=
2205 oauth2_token_service_
->StartRequest(account_id
, oauth2_scopes
, this);
2208 void ProfileSyncService::SetEncryptionPassphrase(const std::string
& passphrase
,
2209 PassphraseType type
) {
2210 // This should only be called when the backend has been initialized.
2211 DCHECK(backend_initialized());
2212 DCHECK(!(type
== IMPLICIT
&& IsUsingSecondaryPassphrase())) <<
2213 "Data is already encrypted using an explicit passphrase";
2214 DCHECK(!(type
== EXPLICIT
&&
2215 passphrase_required_reason_
== syncer::REASON_DECRYPTION
)) <<
2216 "Can not set explicit passphrase when decryption is needed.";
2218 DVLOG(1) << "Setting " << (type
== EXPLICIT
? "explicit" : "implicit")
2219 << " passphrase for encryption.";
2220 if (passphrase_required_reason_
== syncer::REASON_ENCRYPTION
) {
2221 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2222 // keys. Hence, as long as we're not trying to do an invalid passphrase
2223 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2224 // will succeed. If for some reason a new encryption key arrives via
2225 // sync later, the SBH will trigger another OnPassphraseRequired().
2226 passphrase_required_reason_
= syncer::REASON_PASSPHRASE_NOT_REQUIRED
;
2229 backend_
->SetEncryptionPassphrase(passphrase
, type
== EXPLICIT
);
2232 bool ProfileSyncService::SetDecryptionPassphrase(
2233 const std::string
& passphrase
) {
2234 if (IsPassphraseRequired()) {
2235 DVLOG(1) << "Setting passphrase for decryption.";
2236 bool result
= backend_
->SetDecryptionPassphrase(passphrase
);
2237 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result
);
2240 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2241 "IsPassphraseRequired() is false.";
2246 bool ProfileSyncService::EncryptEverythingAllowed() const {
2247 return encrypt_everything_allowed_
;
2250 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed
) {
2251 DCHECK(allowed
|| !backend_initialized() || !EncryptEverythingEnabled());
2252 encrypt_everything_allowed_
= allowed
;
2255 void ProfileSyncService::EnableEncryptEverything() {
2256 DCHECK(EncryptEverythingAllowed());
2258 // Tests override backend_initialized() to always return true, so we
2259 // must check that instead of |backend_initialized_|.
2260 // TODO(akalin): Fix the above. :/
2261 DCHECK(backend_initialized());
2262 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2263 // problems around cancelling encryption in the background (crbug.com/119649).
2264 if (!encrypt_everything_
)
2265 encryption_pending_
= true;
2268 bool ProfileSyncService::encryption_pending() const {
2269 // We may be called during the setup process before we're
2270 // initialized (via IsEncryptedDatatypeEnabled and
2271 // IsPassphraseRequiredForDecryption).
2272 return encryption_pending_
;
2275 bool ProfileSyncService::EncryptEverythingEnabled() const {
2276 DCHECK(backend_initialized_
);
2277 return encrypt_everything_
|| encryption_pending_
;
2280 syncer::ModelTypeSet
ProfileSyncService::GetEncryptedDataTypes() const {
2281 DCHECK(encrypted_types_
.Has(syncer::PASSWORDS
));
2282 // We may be called during the setup process before we're
2283 // initialized. In this case, we default to the sensitive types.
2284 return encrypted_types_
;
2287 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed
) {
2288 if (is_sync_managed
) {
2289 StopImpl(CLEAR_DATA
);
2291 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2292 startup_controller_
->TryStart();
2296 void ProfileSyncService::GoogleSigninSucceeded(const std::string
& account_id
,
2297 const std::string
& username
,
2298 const std::string
& password
) {
2299 if (IsSyncRequested() && !password
.empty()) {
2300 cached_passphrase_
= password
;
2301 // Try to consume the passphrase we just cached. If the sync backend
2302 // is not running yet, the passphrase will remain cached until the
2303 // backend starts up.
2304 ConsumeCachedPassphraseIfPossible();
2306 #if defined(OS_CHROMEOS)
2307 RefreshSpareBootstrapToken(password
);
2309 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE
) {
2310 // Track the fact that we're still waiting for auth to complete.
2311 is_auth_in_progress_
= true;
2315 void ProfileSyncService::GoogleSignedOut(const std::string
& account_id
,
2316 const std::string
& username
) {
2317 sync_disabled_by_admin_
= false;
2318 RequestStop(CLEAR_DATA
);
2320 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2321 need_backup_
= true;
2322 backup_finished_
= false;
2326 void ProfileSyncService::AddObserver(
2327 sync_driver::SyncServiceObserver
* observer
) {
2328 observers_
.AddObserver(observer
);
2331 void ProfileSyncService::RemoveObserver(
2332 sync_driver::SyncServiceObserver
* observer
) {
2333 observers_
.RemoveObserver(observer
);
2336 void ProfileSyncService::AddProtocolEventObserver(
2337 browser_sync::ProtocolEventObserver
* observer
) {
2338 protocol_event_observers_
.AddObserver(observer
);
2339 if (HasSyncingBackend()) {
2340 backend_
->RequestBufferedProtocolEventsAndEnableForwarding();
2344 void ProfileSyncService::RemoveProtocolEventObserver(
2345 browser_sync::ProtocolEventObserver
* observer
) {
2346 protocol_event_observers_
.RemoveObserver(observer
);
2347 if (HasSyncingBackend() &&
2348 !protocol_event_observers_
.might_have_observers()) {
2349 backend_
->DisableProtocolEventForwarding();
2353 void ProfileSyncService::AddTypeDebugInfoObserver(
2354 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2355 type_debug_info_observers_
.AddObserver(type_debug_info_observer
);
2356 if (type_debug_info_observers_
.might_have_observers() &&
2357 backend_initialized_
) {
2358 backend_
->EnableDirectoryTypeDebugInfoForwarding();
2362 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2363 syncer::TypeDebugInfoObserver
* type_debug_info_observer
) {
2364 type_debug_info_observers_
.RemoveObserver(type_debug_info_observer
);
2365 if (!type_debug_info_observers_
.might_have_observers() &&
2366 backend_initialized_
) {
2367 backend_
->DisableDirectoryTypeDebugInfoForwarding();
2371 void ProfileSyncService::AddPreferenceProvider(
2372 SyncTypePreferenceProvider
* provider
) {
2373 DCHECK(!HasPreferenceProvider(provider
))
2374 << "Providers may only be added once!";
2375 preference_providers_
.insert(provider
);
2378 void ProfileSyncService::RemovePreferenceProvider(
2379 SyncTypePreferenceProvider
* provider
) {
2380 DCHECK(HasPreferenceProvider(provider
))
2381 << "Only providers that have been added before can be removed!";
2382 preference_providers_
.erase(provider
);
2385 bool ProfileSyncService::HasPreferenceProvider(
2386 SyncTypePreferenceProvider
* provider
) const {
2387 return preference_providers_
.count(provider
) > 0;
2392 class GetAllNodesRequestHelper
2393 : public base::RefCountedThreadSafe
<GetAllNodesRequestHelper
> {
2395 GetAllNodesRequestHelper(
2396 syncer::ModelTypeSet requested_types
,
2397 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
);
2399 void OnReceivedNodesForTypes(
2400 const std::vector
<syncer::ModelType
>& types
,
2401 ScopedVector
<base::ListValue
> scoped_node_lists
);
2404 friend class base::RefCountedThreadSafe
<GetAllNodesRequestHelper
>;
2405 virtual ~GetAllNodesRequestHelper();
2407 scoped_ptr
<base::ListValue
> result_accumulator_
;
2409 syncer::ModelTypeSet awaiting_types_
;
2410 base::Callback
<void(scoped_ptr
<base::ListValue
>)> callback_
;
2413 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2414 syncer::ModelTypeSet requested_types
,
2415 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
)
2416 : result_accumulator_(new base::ListValue()),
2417 awaiting_types_(requested_types
),
2418 callback_(callback
) {}
2420 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2421 if (!awaiting_types_
.Empty()) {
2423 << "GetAllNodesRequest deleted before request was fulfilled. "
2424 << "Missing types are: " << ModelTypeSetToString(awaiting_types_
);
2428 // Called when the set of nodes for a type or set of types has been returned.
2430 // The nodes for several types can be returned at the same time by specifying
2431 // their types in the |types| array, and putting their results at the
2432 // correspnding indices in the |scoped_node_lists|.
2433 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2434 const std::vector
<syncer::ModelType
>& types
,
2435 ScopedVector
<base::ListValue
> scoped_node_lists
) {
2436 DCHECK_EQ(types
.size(), scoped_node_lists
.size());
2438 // Take unsafe ownership of the node list.
2439 std::vector
<base::ListValue
*> node_lists
;
2440 scoped_node_lists
.release(&node_lists
);
2442 for (size_t i
= 0; i
< node_lists
.size() && i
< types
.size(); ++i
) {
2443 const ModelType type
= types
[i
];
2444 base::ListValue
* node_list
= node_lists
[i
];
2446 // Add these results to our list.
2447 scoped_ptr
<base::DictionaryValue
> type_dict(new base::DictionaryValue());
2448 type_dict
->SetString("type", ModelTypeToString(type
));
2449 type_dict
->Set("nodes", node_list
);
2450 result_accumulator_
->Append(type_dict
.release());
2452 // Remember that this part of the request is satisfied.
2453 awaiting_types_
.Remove(type
);
2456 if (awaiting_types_
.Empty()) {
2457 callback_
.Run(result_accumulator_
.Pass());
2464 void ProfileSyncService::GetAllNodes(
2465 const base::Callback
<void(scoped_ptr
<base::ListValue
>)>& callback
) {
2466 ModelTypeSet directory_types
= GetRegisteredDirectoryDataTypes();
2467 directory_types
.PutAll(syncer::ControlTypes());
2468 scoped_refptr
<GetAllNodesRequestHelper
> helper
=
2469 new GetAllNodesRequestHelper(directory_types
, callback
);
2471 if (!backend_initialized_
) {
2472 // If there's no backend available to fulfill the request, handle it here.
2473 ScopedVector
<base::ListValue
> empty_results
;
2474 std::vector
<ModelType
> type_vector
;
2475 for (ModelTypeSet::Iterator it
= directory_types
.First();
2476 it
.Good(); it
.Inc()) {
2477 type_vector
.push_back(it
.Get());
2478 empty_results
.push_back(new base::ListValue());
2480 helper
->OnReceivedNodesForTypes(type_vector
, empty_results
.Pass());
2482 backend_
->GetAllNodesForTypes(
2484 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes
, helper
));
2488 bool ProfileSyncService::HasObserver(
2489 const sync_driver::SyncServiceObserver
* observer
) const {
2490 return observers_
.HasObserver(observer
);
2493 base::WeakPtr
<syncer::JsController
> ProfileSyncService::GetJsController() {
2494 return sync_js_controller_
.AsWeakPtr();
2497 void ProfileSyncService::SyncEvent(SyncEventCodes code
) {
2498 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code
, MAX_SYNC_EVENT_CODE
);
2502 bool ProfileSyncService::IsSyncAllowedByFlag() {
2503 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2504 switches::kDisableSync
);
2507 bool ProfileSyncService::IsManaged() const {
2508 return sync_prefs_
.IsManaged() || sync_disabled_by_admin_
;
2511 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate
) {
2512 sync_prefs_
.SetSyncRequested(false);
2513 StopImpl(data_fate
);
2516 bool ProfileSyncService::IsSyncRequested() const {
2517 return sync_prefs_
.IsSyncRequested();
2520 SigninManagerBase
* ProfileSyncService::signin() const {
2523 return signin_
->GetOriginal();
2526 void ProfileSyncService::RequestStart() {
2528 sync_prefs_
.SetSyncRequested(true);
2529 DCHECK(!signin_
.get() || signin_
->GetOriginal()->IsAuthenticated());
2530 startup_controller_
->TryStart();
2533 void ProfileSyncService::ReconfigureDatatypeManager() {
2534 // If we haven't initialized yet, don't configure the DTM as it could cause
2535 // association to start before a Directory has even been created.
2536 if (backend_initialized_
) {
2537 DCHECK(backend_
.get());
2538 ConfigureDataTypeManager();
2539 } else if (HasUnrecoverableError()) {
2540 // There is nothing more to configure. So inform the listeners,
2543 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2544 << "Unrecoverable error.";
2546 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2551 syncer::ModelTypeSet
ProfileSyncService::GetDataTypesFromPreferenceProviders()
2553 syncer::ModelTypeSet types
;
2554 for (std::set
<SyncTypePreferenceProvider
*>::const_iterator it
=
2555 preference_providers_
.begin();
2556 it
!= preference_providers_
.end();
2558 types
.PutAll((*it
)->GetPreferredDataTypes());
2563 const DataTypeStatusTable
& ProfileSyncService::data_type_status_table()
2565 return data_type_status_table_
;
2568 void ProfileSyncService::OnInternalUnrecoverableError(
2569 const tracked_objects::Location
& from_here
,
2570 const std::string
& message
,
2571 bool delete_sync_database
,
2572 UnrecoverableErrorReason reason
) {
2573 DCHECK(!HasUnrecoverableError());
2574 unrecoverable_error_reason_
= reason
;
2575 OnUnrecoverableErrorImpl(from_here
, message
, delete_sync_database
);
2578 syncer::SyncManagerFactory::MANAGER_TYPE
2579 ProfileSyncService::GetManagerType() const {
2580 switch (backend_mode_
) {
2582 return syncer::SyncManagerFactory::NORMAL
;
2584 return syncer::SyncManagerFactory::BACKUP
;
2586 return syncer::SyncManagerFactory::ROLLBACK
;
2590 return syncer::SyncManagerFactory::NORMAL
;
2593 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2594 return request_access_token_retry_timer_
.IsRunning();
2597 std::string
ProfileSyncService::GetAccessTokenForTest() const {
2598 return access_token_
;
2601 WeakHandle
<syncer::JsEventHandler
> ProfileSyncService::GetJsEventHandler() {
2602 return MakeWeakHandle(sync_js_controller_
.AsWeakPtr());
2605 syncer::SyncableService
* ProfileSyncService::GetSessionsSyncableService() {
2606 return sessions_sync_manager_
.get();
2609 syncer::SyncableService
* ProfileSyncService::GetDeviceInfoSyncableService() {
2610 return device_info_sync_service_
.get();
2613 sync_driver::SyncService::SyncTokenStatus
2614 ProfileSyncService::GetSyncTokenStatus() const {
2615 SyncTokenStatus status
;
2616 status
.connection_status_update_time
= connection_status_update_time_
;
2617 status
.connection_status
= connection_status_
;
2618 status
.token_request_time
= token_request_time_
;
2619 status
.token_receive_time
= token_receive_time_
;
2620 status
.last_get_token_error
= last_get_token_error_
;
2621 if (request_access_token_retry_timer_
.IsRunning())
2622 status
.next_token_request_time
= next_token_request_time_
;
2626 void ProfileSyncService::OverrideNetworkResourcesForTest(
2627 scoped_ptr
<syncer::NetworkResources
> network_resources
) {
2628 network_resources_
= network_resources
.Pass();
2631 bool ProfileSyncService::HasSyncingBackend() const {
2632 return backend_mode_
!= SYNC
? false : backend_
!= NULL
;
2635 void ProfileSyncService::UpdateFirstSyncTimePref() {
2636 if (!IsSignedIn()) {
2637 // Clear if user's not signed in and rollback is done.
2638 if (backend_mode_
!= ROLLBACK
)
2639 sync_prefs_
.ClearFirstSyncTime();
2640 } else if (sync_prefs_
.GetFirstSyncTime().is_null() &&
2641 backend_mode_
== SYNC
) {
2642 // Set if not set before and it's syncing now.
2643 sync_prefs_
.SetFirstSyncTime(base::Time::Now());
2647 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2648 base::Time first_sync_time
= sync_prefs_
.GetFirstSyncTime();
2649 if (first_sync_time
.is_null())
2652 clear_browsing_data_
.Run(browsing_data_remover_observer_
,
2658 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2659 BrowsingDataRemover::Observer
* observer
) {
2660 browsing_data_remover_observer_
= observer
;
2663 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2664 base::Callback
<void(BrowsingDataRemover::Observer
* observer
,
2668 clear_browsing_data_
= c
;
2671 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2672 DCHECK_EQ(backend_mode_
, SYNC
);
2674 #if defined(ENABLE_PRE_SYNC_BACKUP)
2675 const base::Time last_synced_time
= sync_prefs_
.GetLastSyncedTime();
2676 // Check backup once a day.
2677 if (!last_backup_time_
&&
2678 (last_synced_time
.is_null() ||
2679 base::Time::Now() - last_synced_time
>=
2680 base::TimeDelta::FromDays(1))) {
2681 // If sync thread is set, need to serialize check on sync thread after
2682 // closing backup DB.
2684 sync_thread_
->task_runner()->PostTask(
2686 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2687 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2688 base::ThreadTaskRunnerHandle::Get(),
2689 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2690 weak_factory_
.GetWeakPtr())));
2692 content::BrowserThread::PostTask(
2693 content::BrowserThread::FILE, FROM_HERE
,
2694 base::Bind(syncer::CheckSyncDbLastModifiedTime
,
2695 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2696 base::ThreadTaskRunnerHandle::Get(),
2697 base::Bind(&ProfileSyncService::CheckSyncBackupCallback
,
2698 weak_factory_
.GetWeakPtr())));
2704 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time
) {
2705 last_backup_time_
.reset(new base::Time(backup_time
));
2707 DCHECK(device_info_sync_service_
);
2708 device_info_sync_service_
->UpdateLocalDeviceBackupTime(*last_backup_time_
);
2711 void ProfileSyncService::TryStartSyncAfterBackup() {
2712 startup_controller_
->Reset(GetRegisteredDataTypes());
2713 startup_controller_
->TryStart();
2716 void ProfileSyncService::CleanUpBackup() {
2717 sync_prefs_
.ClearFirstSyncTime();
2718 profile_
->GetIOTaskRunner()->PostTask(
2720 base::Bind(base::IgnoreResult(base::DeleteFile
),
2721 profile_
->GetPath().Append(kSyncBackupDataFolderName
),
2725 bool ProfileSyncService::NeedBackup() const {
2726 return need_backup_
;
2729 base::Time
ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2730 return device_info_sync_service_
->GetLocalDeviceBackupTime();
2733 void ProfileSyncService::FlushDirectory() const {
2734 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2735 // If sync is not initialized yet, we fail silently.
2736 if (backend_initialized_
)
2737 backend_
->FlushDirectory();
2740 base::FilePath
ProfileSyncService::GetDirectoryPathForTest() const {
2741 return directory_path_
;
2744 base::MessageLoop
* ProfileSyncService::GetSyncLoopForTest() const {
2746 return sync_thread_
->message_loop();
2747 } else if (backend_
) {
2748 return backend_
->GetSyncLoopForTesting();
2754 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types
) {
2755 if (backend_initialized_
)
2756 backend_
->RefreshTypesForTest(types
);
2759 void ProfileSyncService::RemoveClientFromServer() const {
2760 if (!backend_initialized_
) return;
2761 const std::string cache_guid
= local_device_
->GetLocalSyncCacheGUID();
2762 std::string birthday
;
2763 syncer::UserShare
* user_share
= GetUserShare();
2764 if (user_share
&& user_share
->directory
.get()) {
2765 birthday
= user_share
->directory
->store_birthday();
2767 if (!access_token_
.empty() && !cache_guid
.empty() && !birthday
.empty()) {
2768 sync_stopped_reporter_
->ReportSyncStopped(
2769 access_token_
, cache_guid
, birthday
);
2773 void ProfileSyncService::OnMemoryPressure(
2774 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level
) {
2775 if (memory_pressure_level
==
2776 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
) {
2777 sync_prefs_
.SetMemoryPressureWarningCount(
2778 sync_prefs_
.GetMemoryPressureWarningCount() + 1);
2782 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2783 int warning_received
= sync_prefs_
.GetMemoryPressureWarningCount();
2785 if (-1 != warning_received
) {
2786 // -1 means it is new client.
2787 if (!sync_prefs_
.DidSyncShutdownCleanly()) {
2788 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2791 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2795 sync_prefs_
.SetMemoryPressureWarningCount(0);
2796 // Will set to true during a clean shutdown, so crash or something else will
2797 // remain this as false.
2798 sync_prefs_
.SetCleanShutdown(false);
2801 const GURL
& ProfileSyncService::sync_service_url() const {
2802 return sync_service_url_
;
2805 std::string
ProfileSyncService::unrecoverable_error_message() const {
2806 return unrecoverable_error_message_
;
2809 tracked_objects::Location
ProfileSyncService::unrecoverable_error_location()
2811 return unrecoverable_error_location_
;