[Sync] Rename PSS::IsSyncEnabled to PSS::IsSyncAllowedByFlag.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blobe33d5021e8f6792a124a0d4afac998776ab7c46c
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"
7 #include <cstddef>
8 #include <map>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/metrics/histogram.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browsing_data/browsing_data_helper.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
33 #include "chrome/browser/net/chrome_cookie_notification_details.h"
34 #include "chrome/browser/password_manager/password_store_factory.h"
35 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
36 #include "chrome/browser/prefs/pref_service_syncable.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/signin/about_signin_internals_factory.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/backend_migrator.h"
43 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
44 #include "chrome/browser/sync/glue/favicon_cache.h"
45 #include "chrome/browser/sync/glue/sync_backend_host.h"
46 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
47 #include "chrome/browser/sync/glue/sync_start_util.h"
48 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
49 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
50 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
51 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
52 #include "chrome/browser/sync/sync_error_controller.h"
53 #include "chrome/browser/sync/sync_stopped_reporter.h"
54 #include "chrome/browser/sync/sync_type_preference_provider.h"
55 #include "chrome/browser/ui/browser.h"
56 #include "chrome/browser/ui/browser_list.h"
57 #include "chrome/browser/ui/browser_window.h"
58 #include "chrome/browser/ui/global_error/global_error_service.h"
59 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
60 #include "chrome/common/chrome_switches.h"
61 #include "chrome/common/chrome_version_info.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/url_constants.h"
64 #include "chrome/grit/generated_resources.h"
65 #include "components/autofill/core/common/autofill_pref_names.h"
66 #include "components/invalidation/invalidation_service.h"
67 #include "components/invalidation/profile_invalidation_provider.h"
68 #include "components/password_manager/core/browser/password_store.h"
69 #include "components/pref_registry/pref_registry_syncable.h"
70 #include "components/signin/core/browser/about_signin_internals.h"
71 #include "components/signin/core/browser/profile_oauth2_token_service.h"
72 #include "components/signin/core/browser/signin_manager.h"
73 #include "components/signin/core/browser/signin_metrics.h"
74 #include "components/sync_driver/change_processor.h"
75 #include "components/sync_driver/data_type_controller.h"
76 #include "components/sync_driver/device_info.h"
77 #include "components/sync_driver/pref_names.h"
78 #include "components/sync_driver/system_encryptor.h"
79 #include "components/sync_driver/user_selectable_sync_type.h"
80 #include "content/public/browser/browser_thread.h"
81 #include "content/public/browser/notification_details.h"
82 #include "content/public/browser/notification_service.h"
83 #include "content/public/browser/notification_source.h"
84 #include "net/cookies/cookie_monster.h"
85 #include "net/url_request/url_request_context_getter.h"
86 #include "sync/api/sync_error.h"
87 #include "sync/internal_api/public/configure_reason.h"
88 #include "sync/internal_api/public/http_bridge_network_resources.h"
89 #include "sync/internal_api/public/network_resources.h"
90 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
91 #include "sync/internal_api/public/shutdown_reason.h"
92 #include "sync/internal_api/public/sync_context_proxy.h"
93 #include "sync/internal_api/public/sync_encryption_handler.h"
94 #include "sync/internal_api/public/util/experiments.h"
95 #include "sync/internal_api/public/util/sync_db_util.h"
96 #include "sync/internal_api/public/util/sync_string_conversions.h"
97 #include "sync/js/js_event_details.h"
98 #include "sync/protocol/sync.pb.h"
99 #include "sync/syncable/directory.h"
100 #include "sync/util/cryptographer.h"
101 #include "ui/base/l10n/l10n_util.h"
102 #include "ui/base/l10n/time_format.h"
104 #if defined(OS_ANDROID)
105 #include "sync/internal_api/public/read_transaction.h"
106 #endif
108 using browser_sync::NotificationServiceSessionsRouter;
109 using browser_sync::ProfileSyncServiceStartBehavior;
110 using browser_sync::SessionsSyncManager;
111 using browser_sync::SyncBackendHost;
112 using sync_driver::ChangeProcessor;
113 using sync_driver::DataTypeController;
114 using sync_driver::DataTypeManager;
115 using sync_driver::DataTypeStatusTable;
116 using sync_driver::DeviceInfoSyncService;
117 using syncer::ModelType;
118 using syncer::ModelTypeSet;
119 using syncer::JsBackend;
120 using syncer::JsController;
121 using syncer::JsEventDetails;
122 using syncer::JsEventHandler;
123 using syncer::ModelSafeRoutingInfo;
124 using syncer::SyncCredentials;
125 using syncer::SyncProtocolError;
126 using syncer::WeakHandle;
128 typedef GoogleServiceAuthError AuthError;
130 const char* ProfileSyncService::kSyncServerUrl =
131 "https://clients4.google.com/chrome-sync";
133 const char* ProfileSyncService::kDevServerUrl =
134 "https://clients4.google.com/chrome-sync/dev";
136 const char kSyncUnrecoverableErrorHistogram[] =
137 "Sync.UnrecoverableErrors";
139 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
140 // Number of initial errors (in sequence) to ignore before applying
141 // exponential back-off rules.
144 // Initial delay for exponential back-off in ms.
145 2000,
147 // Factor by which the waiting time will be multiplied.
150 // Fuzzing percentage. ex: 10% will spread requests randomly
151 // between 90%-100% of the calculated time.
152 0.2, // 20%
154 // Maximum amount of time we are willing to delay our request in ms.
155 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
156 // RequestAccessToken on connection state change after backoff
157 1000 * 3600 * 4, // 4 hours.
159 // Time to keep an entry from being discarded even when it
160 // has no significant state, -1 to never discard.
163 // Don't use initial delay unless the last request was an error.
164 false,
167 static const base::FilePath::CharType kSyncDataFolderName[] =
168 FILE_PATH_LITERAL("Sync Data");
170 static const base::FilePath::CharType kSyncBackupDataFolderName[] =
171 FILE_PATH_LITERAL("Sync Data Backup");
173 namespace {
175 void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
176 Profile* profile,
177 base::Time start,
178 base::Time end) {
179 // BrowsingDataRemover deletes itself when it's done.
180 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
181 profile, start, end);
182 if (observer)
183 remover->AddObserver(observer);
184 remover->Remove(BrowsingDataRemover::REMOVE_ALL,
185 BrowsingDataHelper::ALL);
187 scoped_refptr<password_manager::PasswordStore> password =
188 PasswordStoreFactory::GetForProfile(profile,
189 ServiceAccessType::EXPLICIT_ACCESS);
190 password->RemoveLoginsSyncedBetween(start, end);
193 // Perform the actual sync data folder deletion.
194 // This should only be called on the sync thread.
195 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
196 if (base::DirectoryExists(directory_path)) {
197 if (!base::DeleteFile(directory_path, true))
198 LOG(DFATAL) << "Could not delete the Sync Data folder.";
202 } // anonymous namespace
204 bool ShouldShowActionOnUI(
205 const syncer::SyncProtocolError& error) {
206 return (error.action != syncer::UNKNOWN_ACTION &&
207 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
208 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
211 ProfileSyncService::ProfileSyncService(
212 scoped_ptr<ProfileSyncComponentsFactory> factory,
213 Profile* profile,
214 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
215 ProfileOAuth2TokenService* oauth2_token_service,
216 ProfileSyncServiceStartBehavior start_behavior)
217 : OAuth2TokenService::Consumer("sync"),
218 last_auth_error_(AuthError::AuthErrorNone()),
219 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
220 factory_(factory.Pass()),
221 profile_(profile),
222 sync_prefs_(profile_->GetPrefs()),
223 sync_service_url_(
224 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
225 is_first_time_sync_configure_(false),
226 backend_initialized_(false),
227 sync_disabled_by_admin_(false),
228 is_auth_in_progress_(false),
229 signin_(signin_wrapper.Pass()),
230 unrecoverable_error_reason_(ERROR_REASON_UNSET),
231 expect_sync_configuration_aborted_(false),
232 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
233 encrypt_everything_allowed_(true),
234 encrypt_everything_(false),
235 encryption_pending_(false),
236 configure_status_(DataTypeManager::UNKNOWN),
237 oauth2_token_service_(oauth2_token_service),
238 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
239 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
240 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
241 network_resources_(new syncer::HttpBridgeNetworkResources),
242 backend_mode_(IDLE),
243 need_backup_(false),
244 backup_finished_(false),
245 clear_browsing_data_(base::Bind(&ClearBrowsingData)),
246 browsing_data_remover_observer_(NULL),
247 sync_stopped_reporter_(
248 new browser_sync::SyncStoppedReporter(
249 sync_service_url_,
250 profile_->GetRequestContext(),
251 browser_sync::SyncStoppedReporter::ResultCallback())),
252 weak_factory_(this),
253 startup_controller_weak_factory_(this) {
254 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
255 DCHECK(profile);
256 startup_controller_.reset(new browser_sync::StartupController(
257 start_behavior,
258 oauth2_token_service,
259 &sync_prefs_,
260 signin_.get(),
261 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
262 startup_controller_weak_factory_.GetWeakPtr(),
263 SYNC)));
264 backup_rollback_controller_.reset(new browser_sync::BackupRollbackController(
265 &sync_prefs_,
266 signin_.get(),
267 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
268 startup_controller_weak_factory_.GetWeakPtr(),
269 BACKUP),
270 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
271 startup_controller_weak_factory_.GetWeakPtr(),
272 ROLLBACK)));
273 syncer::SyncableService::StartSyncFlare flare(
274 sync_start_util::GetFlareForSyncableService(profile->GetPath()));
275 scoped_ptr<browser_sync::LocalSessionEventRouter> router(
276 new NotificationServiceSessionsRouter(profile, flare));
278 DCHECK(factory_.get());
279 local_device_ = factory_->CreateLocalDeviceInfoProvider();
280 sessions_sync_manager_.reset(
281 new SessionsSyncManager(profile, local_device_.get(), router.Pass()));
282 device_info_sync_service_.reset(
283 new DeviceInfoSyncService(local_device_.get()));
286 ProfileSyncService::~ProfileSyncService() {
287 sync_prefs_.RemoveSyncPrefObserver(this);
288 // Shutdown() should have been called before destruction.
289 CHECK(!backend_initialized_);
292 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
293 // Exit if sync is disabled.
294 if (IsManaged() || sync_prefs_.IsStartSuppressed())
295 return false;
297 // Sync is logged in if there is a non-empty effective account id.
298 return !signin_->GetAccountIdToUse().empty();
301 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
302 if (!oauth2_token_service_)
303 return false;
305 return oauth2_token_service_->RefreshTokenIsAvailable(
306 signin_->GetAccountIdToUse());
309 void ProfileSyncService::Initialize() {
310 // We clear this here (vs Shutdown) because we want to remember that an error
311 // happened on shutdown so we can display details (message, location) about it
312 // in about:sync.
313 ClearStaleErrors();
315 sync_prefs_.AddSyncPrefObserver(this);
317 // For now, the only thing we can do through policy is to turn sync off.
318 if (IsManaged()) {
319 DisableForUser();
320 return;
323 RegisterAuthNotifications();
325 if (!HasSyncSetupCompleted() || signin_->GetAccountIdToUse().empty()) {
326 // Clean up in case of previous crash / setup abort / signout.
327 DisableForUser();
330 TrySyncDatatypePrefRecovery();
332 #if defined(OS_CHROMEOS)
333 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
334 if (bootstrap_token.empty()) {
335 sync_prefs_.SetEncryptionBootstrapToken(
336 sync_prefs_.GetSpareBootstrapToken());
338 #endif
340 #if !defined(OS_ANDROID)
341 DCHECK(sync_error_controller_ == NULL)
342 << "Initialize() called more than once.";
343 sync_error_controller_.reset(new SyncErrorController(this));
344 AddObserver(sync_error_controller_.get());
345 #endif
347 bool running_rollback = false;
348 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
349 // Backup is needed if user's not signed in or signed in but previous
350 // backup didn't finish, i.e. backend didn't switch from backup to sync.
351 need_backup_ = signin_->GetAccountIdToUse().empty() ||
352 sync_prefs_.GetFirstSyncTime().is_null();
354 // Try to resume rollback if it didn't finish in last session.
355 running_rollback = backup_rollback_controller_->StartRollback();
356 } else {
357 need_backup_ = false;
360 #if defined(ENABLE_PRE_SYNC_BACKUP)
361 if (!running_rollback && signin_->GetAccountIdToUse().empty()) {
362 CleanUpBackup();
364 #else
365 DCHECK(!running_rollback);
366 #endif
368 memory_pressure_listener_.reset(new base::MemoryPressureListener(base::Bind(
369 &ProfileSyncService::OnMemoryPressure, weak_factory_.GetWeakPtr())));
370 startup_controller_->Reset(GetRegisteredDataTypes());
371 startup_controller_->TryStart();
374 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
375 DCHECK(!backend_initialized());
376 if (!HasSyncSetupCompleted())
377 return;
379 // There was a bug where OnUserChoseDatatypes was not properly called on
380 // configuration (see crbug.com/154940). We detect this by checking whether
381 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
382 // completed, it means sync was not properly configured, so we manually
383 // set kSyncKeepEverythingSynced.
384 PrefService* const pref_service = profile_->GetPrefs();
385 if (!pref_service)
386 return;
387 if (GetPreferredDataTypes().Size() > 1)
388 return;
390 const PrefService::Preference* keep_everything_synced =
391 pref_service->FindPreference(
392 sync_driver::prefs::kSyncKeepEverythingSynced);
393 // This will be false if the preference was properly set or if it's controlled
394 // by policy.
395 if (!keep_everything_synced->IsDefaultValue())
396 return;
398 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
399 // types now, before we configure.
400 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
401 sync_prefs_.SetKeepEverythingSynced(true);
402 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
405 void ProfileSyncService::StartSyncingWithServer() {
406 if (backend_)
407 backend_->StartSyncingWithServer();
410 void ProfileSyncService::RegisterAuthNotifications() {
411 oauth2_token_service_->AddObserver(this);
412 if (signin())
413 signin()->AddObserver(this);
416 void ProfileSyncService::UnregisterAuthNotifications() {
417 if (signin())
418 signin()->RemoveObserver(this);
419 oauth2_token_service_->RemoveObserver(this);
422 void ProfileSyncService::RegisterDataTypeController(
423 DataTypeController* data_type_controller) {
424 DCHECK_EQ(
425 directory_data_type_controllers_.count(data_type_controller->type()),
426 0U);
427 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
428 data_type_controller->type()));
429 directory_data_type_controllers_[data_type_controller->type()] =
430 data_type_controller;
433 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
434 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
435 << "Duplicate registration of type " << ModelTypeToString(type);
437 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
438 // fixed and we have some way of telling whether or not this type should be
439 // enabled.
440 non_blocking_data_type_manager_.RegisterType(type, false);
443 void ProfileSyncService::InitializeNonBlockingType(
444 syncer::ModelType type,
445 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
446 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) {
447 non_blocking_data_type_manager_.InitializeType(
448 type, task_runner, type_sync_proxy);
451 bool ProfileSyncService::IsDataTypeControllerRunning(
452 syncer::ModelType type) const {
453 DataTypeController::TypeMap::const_iterator iter =
454 directory_data_type_controllers_.find(type);
455 if (iter == directory_data_type_controllers_.end()) {
456 return false;
458 return iter->second->state() == DataTypeController::RUNNING;
461 browser_sync::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
462 if (!IsDataTypeControllerRunning(syncer::SESSIONS))
463 return NULL;
464 return sessions_sync_manager_.get();
467 browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
468 return sessions_sync_manager_->GetFaviconCache();
471 browser_sync::SyncedWindowDelegatesGetter*
472 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
473 return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
476 sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
477 const {
478 return device_info_sync_service_.get();
481 sync_driver::LocalDeviceInfoProvider*
482 ProfileSyncService::GetLocalDeviceInfoProvider() {
483 return local_device_.get();
486 void ProfileSyncService::GetDataTypeControllerStates(
487 DataTypeController::StateMap* state_map) const {
488 for (DataTypeController::TypeMap::const_iterator iter =
489 directory_data_type_controllers_.begin();
490 iter != directory_data_type_controllers_.end();
491 ++iter)
492 (*state_map)[iter->first] = iter->second.get()->state();
495 SyncCredentials ProfileSyncService::GetCredentials() {
496 SyncCredentials credentials;
497 if (backend_mode_ == SYNC) {
498 credentials.email = signin_->GetEffectiveUsername();
499 DCHECK(!credentials.email.empty());
500 credentials.sync_token = access_token_;
502 if (credentials.sync_token.empty())
503 credentials.sync_token = "credentials_lost";
505 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
508 return credentials;
511 bool ProfileSyncService::ShouldDeleteSyncFolder() {
512 switch (backend_mode_) {
513 case SYNC:
514 return !HasSyncSetupCompleted();
515 case BACKUP:
516 return true;
517 case ROLLBACK:
518 return false;
519 case IDLE:
520 NOTREACHED();
521 return true;
523 return true;
526 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
527 if (!backend_) {
528 NOTREACHED();
529 return;
532 SyncCredentials credentials = GetCredentials();
534 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
535 profile_->GetRequestContext());
537 if (backend_mode_ == SYNC && delete_stale_data)
538 ClearStaleErrors();
540 scoped_ptr<syncer::UnrecoverableErrorHandler>
541 backend_unrecoverable_error_handler(
542 new browser_sync::BackendUnrecoverableErrorHandler(
543 MakeWeakHandle(weak_factory_.GetWeakPtr())));
545 backend_->Initialize(
546 this,
547 sync_thread_.Pass(),
548 GetJsEventHandler(),
549 sync_service_url_,
550 credentials,
551 delete_stale_data,
552 scoped_ptr<syncer::SyncManagerFactory>(
553 new syncer::SyncManagerFactory(GetManagerType())).Pass(),
554 backend_unrecoverable_error_handler.Pass(),
555 &browser_sync::ChromeReportUnrecoverableError,
556 network_resources_.get());
559 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
560 if (encryption_pending())
561 return true;
562 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
563 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
564 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
565 return !Intersection(preferred_types, encrypted_types).Empty();
568 void ProfileSyncService::OnProtocolEvent(
569 const syncer::ProtocolEvent& event) {
570 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
571 protocol_event_observers_,
572 OnProtocolEvent(event));
575 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
576 syncer::ModelType type,
577 const syncer::CommitCounters& counters) {
578 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
579 type_debug_info_observers_,
580 OnCommitCountersUpdated(type, counters));
583 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
584 syncer::ModelType type,
585 const syncer::UpdateCounters& counters) {
586 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
587 type_debug_info_observers_,
588 OnUpdateCountersUpdated(type, counters));
591 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
592 syncer::ModelType type,
593 const syncer::StatusCounters& counters) {
594 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
595 type_debug_info_observers_,
596 OnStatusCountersUpdated(type, counters));
599 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
600 syncer::ModelType type) {
601 DCHECK(syncer::UserTypes().Has(type));
602 if (backend_.get()) {
603 DVLOG(1) << "A data type requested sync startup, but it looks like "
604 "something else beat it to the punch.";
605 return;
608 if (!GetPreferredDataTypes().Has(type)) {
609 // We can get here as datatype SyncableServices are typically wired up
610 // to the native datatype even if sync isn't enabled.
611 DVLOG(1) << "Dropping sync startup request because type "
612 << syncer::ModelTypeToString(type) << "not enabled.";
613 return;
616 startup_controller_->OnDataTypeRequestsSyncStartup(type);
619 void ProfileSyncService::StartUpSlowBackendComponents(
620 ProfileSyncService::BackendMode mode) {
621 DCHECK_NE(IDLE, mode);
622 if (backend_mode_ == mode) {
623 return;
626 // Backend mode transition rules:
627 // * can transit from IDLE to any other non-IDLE mode.
628 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
629 // be explicitly shut down before backup/rollback starts.
630 // * can not transit out of ROLLBACK mode until rollback is finished
631 // (successfully or unsuccessfully).
632 // * can not transit out of BACKUP mode until backup is finished
633 // (successfully or unsuccessfully).
634 // * if backup is needed, can only transit to SYNC if backup is finished,
636 if (backend_mode_ == SYNC) {
637 LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
638 return;
641 if (backend_mode_ == ROLLBACK ||
642 (backend_mode_ == BACKUP && !backup_finished_)) {
643 // Wait for rollback/backup to finish before start new backend.
644 return;
647 if (mode == SYNC && NeedBackup() && !backup_finished_) {
648 if (backend_mode_ != BACKUP)
649 backup_rollback_controller_->StartBackup();
650 return;
653 DVLOG(1) << "Start backend mode: " << mode;
655 if (backend_) {
656 if (mode == SYNC)
657 ShutdownImpl(syncer::SWITCH_MODE_SYNC);
658 else
659 ShutdownImpl(syncer::STOP_SYNC);
662 backend_mode_ = mode;
664 if (backend_mode_ == BACKUP)
665 backup_start_time_ = base::Time::Now();
667 if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
668 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
669 base::Time::Now() - backup_start_time_);
670 backup_start_time_ = base::Time();
673 if (backend_mode_ == ROLLBACK)
674 ClearBrowsingDataSinceFirstSync();
675 else if (backend_mode_ == SYNC)
676 CheckSyncBackupIfNeeded();
678 base::FilePath sync_folder = backend_mode_ == SYNC ?
679 base::FilePath(kSyncDataFolderName) :
680 base::FilePath(kSyncBackupDataFolderName);
682 invalidation::InvalidationService* invalidator = NULL;
683 if (backend_mode_ == SYNC) {
684 invalidation::ProfileInvalidationProvider* provider =
685 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
686 profile_);
687 if (provider)
688 invalidator = provider->GetInvalidationService();
691 directory_path_ = profile_->GetPath().Append(sync_folder);
693 backend_.reset(
694 factory_->CreateSyncBackendHost(
695 profile_->GetDebugName(),
696 profile_,
697 invalidator,
698 sync_prefs_.AsWeakPtr(),
699 sync_folder));
701 // Initialize the backend. Every time we start up a new SyncBackendHost,
702 // we'll want to start from a fresh SyncDB, so delete any old one that might
703 // be there.
704 InitializeBackend(ShouldDeleteSyncFolder());
706 UpdateFirstSyncTimePref();
708 ReportPreviousSessionMemoryWarningCount();
711 void ProfileSyncService::OnGetTokenSuccess(
712 const OAuth2TokenService::Request* request,
713 const std::string& access_token,
714 const base::Time& expiration_time) {
715 DCHECK_EQ(access_token_request_, request);
716 access_token_request_.reset();
717 access_token_ = access_token;
718 token_receive_time_ = base::Time::Now();
719 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
721 if (sync_prefs_.SyncHasAuthError()) {
722 sync_prefs_.SetSyncAuthError(false);
723 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
724 AUTH_ERROR_FIXED,
725 AUTH_ERROR_LIMIT);
728 if (HasSyncingBackend())
729 backend_->UpdateCredentials(GetCredentials());
730 else
731 startup_controller_->TryStart();
734 void ProfileSyncService::OnGetTokenFailure(
735 const OAuth2TokenService::Request* request,
736 const GoogleServiceAuthError& error) {
737 DCHECK_EQ(access_token_request_, request);
738 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
739 access_token_request_.reset();
740 last_get_token_error_ = error;
741 switch (error.state()) {
742 case GoogleServiceAuthError::CONNECTION_FAILED:
743 case GoogleServiceAuthError::REQUEST_CANCELED:
744 case GoogleServiceAuthError::SERVICE_ERROR:
745 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
746 // Transient error. Retry after some time.
747 request_access_token_backoff_.InformOfRequest(false);
748 next_token_request_time_ = base::Time::Now() +
749 request_access_token_backoff_.GetTimeUntilRelease();
750 request_access_token_retry_timer_.Start(
751 FROM_HERE,
752 request_access_token_backoff_.GetTimeUntilRelease(),
753 base::Bind(&ProfileSyncService::RequestAccessToken,
754 weak_factory_.GetWeakPtr()));
755 NotifyObservers();
756 break;
758 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
759 if (!sync_prefs_.SyncHasAuthError()) {
760 sync_prefs_.SetSyncAuthError(true);
761 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
762 AUTH_ERROR_ENCOUNTERED,
763 AUTH_ERROR_LIMIT);
765 // Fallthrough.
767 default: {
768 if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
769 LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
771 // Show error to user.
772 UpdateAuthErrorState(error);
777 void ProfileSyncService::OnRefreshTokenAvailable(
778 const std::string& account_id) {
779 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
780 // fixed.
781 tracked_objects::ScopedTracker tracking_profile(
782 FROM_HERE_WITH_EXPLICIT_FUNCTION(
783 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
785 if (account_id == signin_->GetAccountIdToUse())
786 OnRefreshTokensLoaded();
789 void ProfileSyncService::OnRefreshTokenRevoked(
790 const std::string& account_id) {
791 if (!IsOAuthRefreshTokenAvailable()) {
792 access_token_.clear();
793 // The additional check around IsOAuthRefreshTokenAvailable() above
794 // prevents us sounding the alarm if we actually have a valid token but
795 // a refresh attempt failed for any variety of reasons
796 // (e.g. flaky network). It's possible the token we do have is also
797 // invalid, but in that case we should already have (or can expect) an
798 // auth error sent from the sync backend.
799 UpdateAuthErrorState(
800 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
804 void ProfileSyncService::OnRefreshTokensLoaded() {
805 // This notification gets fired when OAuth2TokenService loads the tokens
806 // from storage.
807 // Initialize the backend if sync is enabled. If the sync token was
808 // not loaded, GetCredentials() will generate invalid credentials to
809 // cause the backend to generate an auth error (crbug.com/121755).
810 if (HasSyncingBackend()) {
811 RequestAccessToken();
812 } else {
813 startup_controller_->TryStart();
817 void ProfileSyncService::Shutdown() {
818 UnregisterAuthNotifications();
820 ShutdownImpl(syncer::BROWSER_SHUTDOWN);
821 if (sync_error_controller_) {
822 // Destroy the SyncErrorController when the service shuts down for good.
823 RemoveObserver(sync_error_controller_.get());
824 sync_error_controller_.reset();
827 if (sync_thread_)
828 sync_thread_->Stop();
831 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
832 if (!backend_) {
833 if (reason == syncer::ShutdownReason::DISABLE_SYNC && sync_thread_) {
834 // If the backend is already shut down when a DISABLE_SYNC happens,
835 // the data directory needs to be cleaned up here.
836 sync_thread_->message_loop()->PostTask(FROM_HERE,
837 base::Bind(&DeleteSyncDataFolder, directory_path_));
839 return;
842 if (reason == syncer::ShutdownReason::STOP_SYNC
843 || reason == syncer::ShutdownReason::DISABLE_SYNC) {
844 RemoveClientFromServer();
847 non_blocking_data_type_manager_.DisconnectSyncBackend();
849 // First, we spin down the backend to stop change processing as soon as
850 // possible.
851 base::Time shutdown_start_time = base::Time::Now();
852 backend_->StopSyncingForShutdown();
854 // Stop all data type controllers, if needed. Note that until Stop
855 // completes, it is possible in theory to have a ChangeProcessor apply a
856 // change from a native model. In that case, it will get applied to the sync
857 // database (which doesn't get destroyed until we destroy the backend below)
858 // as an unsynced change. That will be persisted, and committed on restart.
859 if (directory_data_type_manager_) {
860 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
861 // When aborting as part of shutdown, we should expect an aborted sync
862 // configure result, else we'll dcheck when we try to read the sync error.
863 expect_sync_configuration_aborted_ = true;
864 directory_data_type_manager_->Stop();
866 directory_data_type_manager_.reset();
869 // Shutdown the migrator before the backend to ensure it doesn't pull a null
870 // snapshot.
871 migrator_.reset();
872 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
874 // Move aside the backend so nobody else tries to use it while we are
875 // shutting it down.
876 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
877 if (doomed_backend) {
878 sync_thread_ = doomed_backend->Shutdown(reason);
879 doomed_backend.reset();
881 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
882 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
884 weak_factory_.InvalidateWeakPtrs();
886 if (backend_mode_ == SYNC)
887 startup_controller_->Reset(GetRegisteredDataTypes());
889 // Don't let backup block sync regardless backup succeeded or not.
890 if (backend_mode_ == BACKUP)
891 backup_finished_ = true;
893 // Sync could be blocked by rollback/backup. Post task to check whether sync
894 // should start after shutting down rollback/backup backend.
895 if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
896 reason != syncer::SWITCH_MODE_SYNC &&
897 reason != syncer::BROWSER_SHUTDOWN) {
898 base::MessageLoop::current()->PostTask(
899 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
900 startup_controller_weak_factory_.GetWeakPtr()));
903 // Clear various flags.
904 backend_mode_ = IDLE;
905 expect_sync_configuration_aborted_ = false;
906 is_auth_in_progress_ = false;
907 backend_initialized_ = false;
908 cached_passphrase_.clear();
909 encryption_pending_ = false;
910 encrypt_everything_ = false;
911 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
912 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
913 request_access_token_retry_timer_.Stop();
914 // Revert to "no auth error".
915 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
916 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
918 NotifyObservers();
920 // Mark this as a clean shutdown(without crash).
921 sync_prefs_.SetCleanShutdown(true);
924 void ProfileSyncService::DisableForUser() {
925 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
926 // PSS clients don't think we're set up while we're shutting down.
927 sync_prefs_.ClearPreferences();
928 ClearUnrecoverableError();
929 ShutdownImpl(syncer::DISABLE_SYNC);
932 bool ProfileSyncService::HasSyncSetupCompleted() const {
933 return sync_prefs_.HasSyncSetupCompleted();
936 void ProfileSyncService::SetSyncSetupCompleted() {
937 sync_prefs_.SetSyncSetupCompleted();
940 void ProfileSyncService::UpdateLastSyncedTime() {
941 sync_prefs_.SetLastSyncedTime(base::Time::Now());
944 void ProfileSyncService::NotifyObservers() {
945 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
946 OnStateChanged());
949 void ProfileSyncService::NotifySyncCycleCompleted() {
950 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
951 OnSyncCycleCompleted());
954 void ProfileSyncService::ClearStaleErrors() {
955 ClearUnrecoverableError();
956 last_actionable_error_ = SyncProtocolError();
957 // Clear the data type errors as well.
958 if (directory_data_type_manager_.get())
959 directory_data_type_manager_->ResetDataTypeErrors();
963 void ProfileSyncService::ClearUnrecoverableError() {
964 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
965 unrecoverable_error_message_.clear();
966 unrecoverable_error_location_ = tracked_objects::Location();
969 // An invariant has been violated. Transition to an error state where we try
970 // to do as little work as possible, to avoid further corruption or crashes.
971 void ProfileSyncService::OnUnrecoverableError(
972 const tracked_objects::Location& from_here,
973 const std::string& message) {
974 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
975 // interface are assumed to originate within the syncer.
976 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
977 OnUnrecoverableErrorImpl(from_here, message, true);
980 void ProfileSyncService::OnUnrecoverableErrorImpl(
981 const tracked_objects::Location& from_here,
982 const std::string& message,
983 bool delete_sync_database) {
984 DCHECK(HasUnrecoverableError());
985 unrecoverable_error_message_ = message;
986 unrecoverable_error_location_ = from_here;
988 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
989 unrecoverable_error_reason_,
990 ERROR_REASON_LIMIT);
991 std::string location;
992 from_here.Write(true, true, &location);
993 LOG(ERROR)
994 << "Unrecoverable error detected at " << location
995 << " -- ProfileSyncService unusable: " << message;
997 // Shut all data types down.
998 base::MessageLoop::current()->PostTask(FROM_HERE,
999 base::Bind(&ProfileSyncService::ShutdownImpl,
1000 weak_factory_.GetWeakPtr(),
1001 delete_sync_database ?
1002 syncer::DISABLE_SYNC : syncer::STOP_SYNC));
1005 void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
1006 if (!backend_initialized_)
1007 return;
1008 directory_data_type_manager_->ReenableType(type);
1011 void ProfileSyncService::UpdateBackendInitUMA(bool success) {
1012 if (backend_mode_ != SYNC)
1013 return;
1015 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
1017 if (is_first_time_sync_configure_) {
1018 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
1019 } else {
1020 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
1023 base::Time on_backend_initialized_time = base::Time::Now();
1024 base::TimeDelta delta = on_backend_initialized_time -
1025 startup_controller_->start_backend_time();
1026 if (is_first_time_sync_configure_) {
1027 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1028 } else {
1029 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1033 void ProfileSyncService::PostBackendInitialization() {
1034 // Never get here for backup / restore.
1035 DCHECK_EQ(backend_mode_, SYNC);
1037 if (last_backup_time_) {
1038 DCHECK(device_info_sync_service_);
1039 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1042 if (protocol_event_observers_.might_have_observers()) {
1043 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1046 non_blocking_data_type_manager_.ConnectSyncBackend(
1047 backend_->GetSyncContextProxy());
1049 if (type_debug_info_observers_.might_have_observers()) {
1050 backend_->EnableDirectoryTypeDebugInfoForwarding();
1053 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1054 // backend is initialized. We want to call this before notifying observers in
1055 // case this operation affects the "passphrase required" status.
1056 ConsumeCachedPassphraseIfPossible();
1058 // The very first time the backend initializes is effectively the first time
1059 // we can say we successfully "synced". LastSyncedTime will only be null in
1060 // this case, because the pref wasn't restored on StartUp.
1061 if (sync_prefs_.GetLastSyncedTime().is_null()) {
1062 UpdateLastSyncedTime();
1065 if (startup_controller_->auto_start_enabled() && !FirstSetupInProgress()) {
1066 // Backend is initialized but we're not in sync setup, so this must be an
1067 // autostart - mark our sync setup as completed and we'll start syncing
1068 // below.
1069 SetSyncSetupCompleted();
1072 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1073 // data type configuration because observer may flag setup as complete and
1074 // trigger data type configuration.
1075 if (HasSyncSetupCompleted()) {
1076 ConfigureDataTypeManager();
1077 } else {
1078 DCHECK(FirstSetupInProgress());
1081 NotifyObservers();
1084 void ProfileSyncService::OnBackendInitialized(
1085 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1086 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1087 debug_info_listener,
1088 const std::string& cache_guid,
1089 bool success) {
1090 UpdateBackendInitUMA(success);
1092 if (!success) {
1093 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1094 // and surface error UI to alert the user sync has stopped.
1095 // Keep the directory around for now so that on restart we will retry
1096 // again and potentially succeed in presence of transient file IO failures
1097 // or permissions issues, etc.
1099 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1100 // Unlike every other UnrecoverableError, it does not delete our sync data.
1101 // This exception made sense at the time it was implemented, but our new
1102 // directory corruption recovery mechanism makes it obsolete. By the time
1103 // we get here, we will have already tried and failed to delete the
1104 // directory. It would be no big deal if we tried to delete it again.
1105 OnInternalUnrecoverableError(FROM_HERE,
1106 "BackendInitialize failure",
1107 false,
1108 ERROR_REASON_BACKEND_INIT_FAILURE);
1109 return;
1112 backend_initialized_ = true;
1114 sync_js_controller_.AttachJsBackend(js_backend);
1115 debug_info_listener_ = debug_info_listener;
1117 SigninClient* signin_client =
1118 ChromeSigninClientFactory::GetForProfile(profile_);
1119 DCHECK(signin_client);
1120 std::string signin_scoped_device_id =
1121 signin_client->GetSigninScopedDeviceId();
1123 // Initialize local device info.
1124 local_device_->Initialize(cache_guid, signin_scoped_device_id);
1126 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1127 non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1129 // Give the DataTypeControllers a handle to the now initialized backend
1130 // as a UserShare.
1131 for (DataTypeController::TypeMap::iterator it =
1132 directory_data_type_controllers_.begin();
1133 it != directory_data_type_controllers_.end(); ++it) {
1134 it->second->OnUserShareReady(GetUserShare());
1137 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1138 ConfigureDataTypeManager();
1139 else
1140 PostBackendInitialization();
1143 void ProfileSyncService::OnSyncCycleCompleted() {
1144 UpdateLastSyncedTime();
1145 if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1146 // Trigger garbage collection of old sessions now that we've downloaded
1147 // any new session data.
1148 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
1149 &SessionsSyncManager::DoGarbageCollection,
1150 base::AsWeakPtr(sessions_sync_manager_.get())));
1152 DVLOG(2) << "Notifying observers sync cycle completed";
1153 NotifySyncCycleCompleted();
1156 void ProfileSyncService::OnExperimentsChanged(
1157 const syncer::Experiments& experiments) {
1158 if (current_experiments_.Matches(experiments))
1159 return;
1161 current_experiments_ = experiments;
1163 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1164 experiments.gcm_invalidations_enabled);
1165 profile()->GetPrefs()->SetBoolean(
1166 autofill::prefs::kAutofillWalletSyncExperimentEnabled,
1167 experiments.wallet_sync_enabled);
1170 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1171 is_auth_in_progress_ = false;
1172 last_auth_error_ = error;
1174 NotifyObservers();
1177 namespace {
1179 AuthError ConnectionStatusToAuthError(
1180 syncer::ConnectionStatus status) {
1181 switch (status) {
1182 case syncer::CONNECTION_OK:
1183 return AuthError::AuthErrorNone();
1184 break;
1185 case syncer::CONNECTION_AUTH_ERROR:
1186 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1187 break;
1188 case syncer::CONNECTION_SERVER_ERROR:
1189 return AuthError(AuthError::CONNECTION_FAILED);
1190 break;
1191 default:
1192 NOTREACHED();
1193 return AuthError(AuthError::CONNECTION_FAILED);
1197 } // namespace
1199 void ProfileSyncService::OnConnectionStatusChange(
1200 syncer::ConnectionStatus status) {
1201 connection_status_update_time_ = base::Time::Now();
1202 connection_status_ = status;
1203 if (status == syncer::CONNECTION_AUTH_ERROR) {
1204 // Sync server returned error indicating that access token is invalid. It
1205 // could be either expired or access is revoked. Let's request another
1206 // access token and if access is revoked then request for token will fail
1207 // with corresponding error. If access token is repeatedly reported
1208 // invalid, there may be some issues with server, e.g. authentication
1209 // state is inconsistent on sync and token server. In that case, we
1210 // backoff token requests exponentially to avoid hammering token server
1211 // too much and to avoid getting same token due to token server's caching
1212 // policy. |request_access_token_retry_timer_| is used to backoff request
1213 // triggered by both auth error and failure talking to GAIA server.
1214 // Therefore, we're likely to reach the backoff ceiling more quickly than
1215 // you would expect from looking at the BackoffPolicy if both types of
1216 // errors happen. We shouldn't receive two errors back-to-back without
1217 // attempting a token/sync request in between, thus crank up request delay
1218 // unnecessary. This is because we won't make a sync request if we hit an
1219 // error until GAIA succeeds at sending a new token, and we won't request
1220 // a new token unless sync reports a token failure. But to be safe, don't
1221 // schedule request if this happens.
1222 if (request_access_token_retry_timer_.IsRunning()) {
1223 // The timer to perform a request later is already running; nothing
1224 // further needs to be done at this point.
1225 } else if (request_access_token_backoff_.failure_count() == 0) {
1226 // First time request without delay. Currently invalid token is used
1227 // to initialize sync backend and we'll always end up here. We don't
1228 // want to delay initialization.
1229 request_access_token_backoff_.InformOfRequest(false);
1230 RequestAccessToken();
1231 } else {
1232 request_access_token_backoff_.InformOfRequest(false);
1233 request_access_token_retry_timer_.Start(
1234 FROM_HERE,
1235 request_access_token_backoff_.GetTimeUntilRelease(),
1236 base::Bind(&ProfileSyncService::RequestAccessToken,
1237 weak_factory_.GetWeakPtr()));
1239 } else {
1240 // Reset backoff time after successful connection.
1241 if (status == syncer::CONNECTION_OK) {
1242 // Request shouldn't be scheduled at this time. But if it is, it's
1243 // possible that sync flips between OK and auth error states rapidly,
1244 // thus hammers token server. To be safe, only reset backoff delay when
1245 // no scheduled request.
1246 if (request_access_token_retry_timer_.IsRunning()) {
1247 NOTREACHED();
1248 } else {
1249 request_access_token_backoff_.Reset();
1253 const GoogleServiceAuthError auth_error =
1254 ConnectionStatusToAuthError(status);
1255 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1256 UpdateAuthErrorState(auth_error);
1260 void ProfileSyncService::StopSyncingPermanently() {
1261 sync_prefs_.SetStartSuppressed(true);
1262 DisableForUser();
1265 void ProfileSyncService::OnPassphraseRequired(
1266 syncer::PassphraseRequiredReason reason,
1267 const sync_pb::EncryptedData& pending_keys) {
1268 DCHECK(backend_.get());
1269 DCHECK(backend_->IsNigoriEnabled());
1271 // TODO(lipalani) : add this check to other locations as well.
1272 if (HasUnrecoverableError()) {
1273 // When unrecoverable error is detected we post a task to shutdown the
1274 // backend. The task might not have executed yet.
1275 return;
1278 DVLOG(1) << "Passphrase required with reason: "
1279 << syncer::PassphraseRequiredReasonToString(reason);
1280 passphrase_required_reason_ = reason;
1282 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1283 if (directory_data_type_manager_) {
1284 // Reconfigure without the encrypted types (excluded implicitly via the
1285 // failed datatypes handler).
1286 directory_data_type_manager_->Configure(types,
1287 syncer::CONFIGURE_REASON_CRYPTO);
1290 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1292 // Notify observers that the passphrase status may have changed.
1293 NotifyObservers();
1296 void ProfileSyncService::OnPassphraseAccepted() {
1297 DVLOG(1) << "Received OnPassphraseAccepted.";
1299 // If the pending keys were resolved via keystore, it's possible we never
1300 // consumed our cached passphrase. Clear it now.
1301 if (!cached_passphrase_.empty())
1302 cached_passphrase_.clear();
1304 // Reset passphrase_required_reason_ since we know we no longer require the
1305 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1306 // because that can be called by OnPassphraseRequired() if no encrypted data
1307 // types are enabled, and we don't want to clobber the true passphrase error.
1308 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1310 // Make sure the data types that depend on the passphrase are started at
1311 // this time.
1312 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1313 if (directory_data_type_manager_) {
1314 // Re-enable any encrypted types if necessary.
1315 directory_data_type_manager_->Configure(types,
1316 syncer::CONFIGURE_REASON_CRYPTO);
1319 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1321 NotifyObservers();
1324 void ProfileSyncService::OnEncryptedTypesChanged(
1325 syncer::ModelTypeSet encrypted_types,
1326 bool encrypt_everything) {
1327 encrypted_types_ = encrypted_types;
1328 encrypt_everything_ = encrypt_everything;
1329 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1330 DVLOG(1) << "Encrypted types changed to "
1331 << syncer::ModelTypeSetToString(encrypted_types_)
1332 << " (encrypt everything is set to "
1333 << (encrypt_everything_ ? "true" : "false") << ")";
1334 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1336 NotifyObservers();
1339 void ProfileSyncService::OnEncryptionComplete() {
1340 DVLOG(1) << "Encryption complete";
1341 if (encryption_pending_ && encrypt_everything_) {
1342 encryption_pending_ = false;
1343 // This is to nudge the integration tests when encryption is
1344 // finished.
1345 NotifyObservers();
1349 void ProfileSyncService::OnMigrationNeededForTypes(
1350 syncer::ModelTypeSet types) {
1351 DCHECK(backend_initialized_);
1352 DCHECK(directory_data_type_manager_.get());
1354 // Migrator must be valid, because we don't sync until it is created and this
1355 // callback originates from a sync cycle.
1356 migrator_->MigrateTypes(types);
1359 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1360 last_actionable_error_ = error;
1361 DCHECK_NE(last_actionable_error_.action,
1362 syncer::UNKNOWN_ACTION);
1363 switch (error.action) {
1364 case syncer::UPGRADE_CLIENT:
1365 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1366 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1367 case syncer::STOP_AND_RESTART_SYNC:
1368 // TODO(lipalani) : if setup in progress we want to display these
1369 // actions in the popup. The current experience might not be optimal for
1370 // the user. We just dismiss the dialog.
1371 if (startup_controller_->setup_in_progress()) {
1372 StopSyncingPermanently();
1373 expect_sync_configuration_aborted_ = true;
1375 // Trigger an unrecoverable error to stop syncing.
1376 OnInternalUnrecoverableError(FROM_HERE,
1377 last_actionable_error_.error_description,
1378 true,
1379 ERROR_REASON_ACTIONABLE_ERROR);
1380 break;
1381 case syncer::DISABLE_SYNC_AND_ROLLBACK:
1382 backup_rollback_controller_->OnRollbackReceived();
1383 // Fall through to shutdown backend and sign user out.
1384 case syncer::DISABLE_SYNC_ON_CLIENT:
1385 StopSyncingPermanently();
1386 #if !defined(OS_CHROMEOS)
1387 // On desktop Chrome, sign out the user after a dashboard clear.
1388 // Skip sign out on ChromeOS/Android.
1389 if (!startup_controller_->auto_start_enabled()) {
1390 SigninManagerFactory::GetForProfile(profile_)->SignOut(
1391 signin_metrics::SERVER_FORCED_DISABLE);
1393 #endif
1394 break;
1395 case syncer::ROLLBACK_DONE:
1396 backup_rollback_controller_->OnRollbackDone();
1397 break;
1398 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1399 // Sync disabled by domain admin. we should stop syncing until next
1400 // restart.
1401 sync_disabled_by_admin_ = true;
1402 ShutdownImpl(syncer::DISABLE_SYNC);
1403 break;
1404 default:
1405 NOTREACHED();
1407 NotifyObservers();
1409 if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1410 (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1411 !backup_rollback_controller_->StartRollback())) {
1412 // Clean up backup data for sign-out only or when rollback is disabled.
1413 CleanUpBackup();
1414 } else if (error.action == syncer::ROLLBACK_DONE) {
1415 // Shut down ROLLBACK backend and delete backup DB.
1416 ShutdownImpl(syncer::DISABLE_SYNC);
1417 sync_prefs_.ClearFirstSyncTime();
1421 void ProfileSyncService::OnConfigureDone(
1422 const DataTypeManager::ConfigureResult& result) {
1423 configure_status_ = result.status;
1424 data_type_status_table_ = result.data_type_status_table;
1426 if (backend_mode_ != SYNC) {
1427 if (configure_status_ == DataTypeManager::OK) {
1428 StartSyncingWithServer();
1430 // Backup is done after models are associated.
1431 if (backend_mode_ == BACKUP)
1432 backup_finished_ = true;
1434 // Asynchronously check whether sync needs to start.
1435 base::MessageLoop::current()->PostTask(
1436 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1437 startup_controller_weak_factory_.GetWeakPtr()));
1438 } else if (!expect_sync_configuration_aborted_) {
1439 DVLOG(1) << "Backup/rollback backend failed to configure.";
1440 ShutdownImpl(syncer::STOP_SYNC);
1443 return;
1446 // We should have cleared our cached passphrase before we get here (in
1447 // OnBackendInitialized()).
1448 DCHECK(cached_passphrase_.empty());
1450 if (!sync_configure_start_time_.is_null()) {
1451 if (result.status == DataTypeManager::OK) {
1452 base::Time sync_configure_stop_time = base::Time::Now();
1453 base::TimeDelta delta = sync_configure_stop_time -
1454 sync_configure_start_time_;
1455 if (is_first_time_sync_configure_) {
1456 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1457 } else {
1458 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1459 delta);
1462 sync_configure_start_time_ = base::Time();
1465 // Notify listeners that configuration is done.
1466 content::NotificationService::current()->Notify(
1467 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1468 content::Source<ProfileSyncService>(this),
1469 content::NotificationService::NoDetails());
1471 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1472 // The possible status values:
1473 // ABORT - Configuration was aborted. This is not an error, if
1474 // initiated by user.
1475 // OK - Some or all types succeeded.
1476 // Everything else is an UnrecoverableError. So treat it as such.
1478 // First handle the abort case.
1479 if (configure_status_ == DataTypeManager::ABORTED &&
1480 expect_sync_configuration_aborted_) {
1481 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1482 expect_sync_configuration_aborted_ = false;
1483 return;
1486 // Handle unrecoverable error.
1487 if (configure_status_ != DataTypeManager::OK) {
1488 // Something catastrophic had happened. We should only have one
1489 // error representing it.
1490 syncer::SyncError error =
1491 data_type_status_table_.GetUnrecoverableError();
1492 DCHECK(error.IsSet());
1493 std::string message =
1494 "Sync configuration failed with status " +
1495 DataTypeManager::ConfigureStatusToString(configure_status_) +
1496 " caused by " +
1497 syncer::ModelTypeSetToString(
1498 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1499 ": " + error.message();
1500 LOG(ERROR) << "ProfileSyncService error: " << message;
1501 OnInternalUnrecoverableError(error.location(),
1502 message,
1503 true,
1504 ERROR_REASON_CONFIGURATION_FAILURE);
1505 return;
1508 // We should never get in a state where we have no encrypted datatypes
1509 // enabled, and yet we still think we require a passphrase for decryption.
1510 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1511 !IsEncryptedDatatypeEnabled()));
1513 // This must be done before we start syncing with the server to avoid
1514 // sending unencrypted data up on a first time sync.
1515 if (encryption_pending_)
1516 backend_->EnableEncryptEverything();
1517 NotifyObservers();
1519 if (migrator_.get() &&
1520 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1521 // Migration in progress. Let the migrator know we just finished
1522 // configuring something. It will be up to the migrator to call
1523 // StartSyncingWithServer() if migration is now finished.
1524 migrator_->OnConfigureDone(result);
1525 } else {
1526 StartSyncingWithServer();
1530 void ProfileSyncService::OnConfigureStart() {
1531 sync_configure_start_time_ = base::Time::Now();
1532 NotifyObservers();
1535 ProfileSyncService::SyncStatusSummary
1536 ProfileSyncService::QuerySyncStatusSummary() {
1537 if (HasUnrecoverableError()) {
1538 return UNRECOVERABLE_ERROR;
1539 } else if (!backend_) {
1540 return NOT_ENABLED;
1541 } else if (backend_mode_ == BACKUP) {
1542 return BACKUP_USER_DATA;
1543 } else if (backend_mode_ == ROLLBACK) {
1544 return ROLLBACK_USER_DATA;
1545 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1546 return SETUP_INCOMPLETE;
1547 } else if (
1548 backend_.get() && HasSyncSetupCompleted() &&
1549 directory_data_type_manager_.get() &&
1550 directory_data_type_manager_->state() == DataTypeManager::STOPPED) {
1551 return DATATYPES_NOT_INITIALIZED;
1552 } else if (SyncActive()) {
1553 return INITIALIZED;
1555 return UNKNOWN_ERROR;
1558 std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1559 SyncStatusSummary status = QuerySyncStatusSummary();
1561 std::string config_status_str =
1562 configure_status_ != DataTypeManager::UNKNOWN ?
1563 DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1565 switch (status) {
1566 case UNRECOVERABLE_ERROR:
1567 return "Unrecoverable error detected";
1568 case NOT_ENABLED:
1569 return "Syncing not enabled";
1570 case SETUP_INCOMPLETE:
1571 return "First time sync setup incomplete";
1572 case DATATYPES_NOT_INITIALIZED:
1573 return "Datatypes not fully initialized";
1574 case INITIALIZED:
1575 return "Sync service initialized";
1576 case BACKUP_USER_DATA:
1577 return "Backing-up user data. Status: " + config_status_str;
1578 case ROLLBACK_USER_DATA:
1579 return "Restoring user data. Status: " + config_status_str;
1580 default:
1581 return "Status unknown: Internal error?";
1585 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1586 return startup_controller_->GetBackendInitializationStateString();
1589 bool ProfileSyncService::auto_start_enabled() const {
1590 return startup_controller_->auto_start_enabled();
1593 bool ProfileSyncService::setup_in_progress() const {
1594 return startup_controller_->setup_in_progress();
1597 bool ProfileSyncService::QueryDetailedSyncStatus(
1598 SyncBackendHost::Status* result) {
1599 if (backend_.get() && backend_initialized_) {
1600 *result = backend_->GetDetailedStatus();
1601 return true;
1602 } else {
1603 SyncBackendHost::Status status;
1604 status.sync_protocol_error = last_actionable_error_;
1605 *result = status;
1606 return false;
1610 const AuthError& ProfileSyncService::GetAuthError() const {
1611 return last_auth_error_;
1614 bool ProfileSyncService::FirstSetupInProgress() const {
1615 return !HasSyncSetupCompleted() && startup_controller_->setup_in_progress();
1618 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1619 // This method is a no-op if |setup_in_progress_| remains unchanged.
1620 if (startup_controller_->setup_in_progress() == setup_in_progress)
1621 return;
1623 startup_controller_->set_setup_in_progress(setup_in_progress);
1624 if (!setup_in_progress && backend_initialized())
1625 ReconfigureDatatypeManager();
1626 NotifyObservers();
1629 bool ProfileSyncService::SyncActive() const {
1630 return backend_initialized_ && backend_mode_ == SYNC &&
1631 directory_data_type_manager_ &&
1632 directory_data_type_manager_->state() != DataTypeManager::STOPPED;
1635 bool ProfileSyncService::backend_initialized() const {
1636 return backend_initialized_;
1639 ProfileSyncService::BackendMode ProfileSyncService::backend_mode() const {
1640 return backend_mode_;
1643 bool ProfileSyncService::ConfigurationDone() const {
1644 return directory_data_type_manager_ &&
1645 directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
1648 bool ProfileSyncService::waiting_for_auth() const {
1649 return is_auth_in_progress_;
1652 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1653 return current_experiments_;
1656 bool ProfileSyncService::HasUnrecoverableError() const {
1657 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1660 bool ProfileSyncService::IsPassphraseRequired() const {
1661 return passphrase_required_reason_ !=
1662 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1665 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1666 // If there is an encrypted datatype enabled and we don't have the proper
1667 // passphrase, we must prompt the user for a passphrase. The only way for the
1668 // user to avoid entering their passphrase is to disable the encrypted types.
1669 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1672 base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1673 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
1674 if (last_synced_time.is_null())
1675 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1677 base::TimeDelta time_since_last_sync = base::Time::Now() - last_synced_time;
1679 if (time_since_last_sync < base::TimeDelta::FromMinutes(1))
1680 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1682 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1683 ui::TimeFormat::LENGTH_SHORT,
1684 time_since_last_sync);
1687 void ProfileSyncService::UpdateSelectedTypesHistogram(
1688 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1689 if (!HasSyncSetupCompleted() ||
1690 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1691 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1694 // Only log the data types that are shown in the sync settings ui.
1695 // Note: the order of these types must match the ordering of
1696 // the respective types in ModelType
1697 const sync_driver::user_selectable_type::UserSelectableSyncType
1698 user_selectable_types[] = {
1699 sync_driver::user_selectable_type::BOOKMARKS,
1700 sync_driver::user_selectable_type::PREFERENCES,
1701 sync_driver::user_selectable_type::PASSWORDS,
1702 sync_driver::user_selectable_type::AUTOFILL,
1703 sync_driver::user_selectable_type::THEMES,
1704 sync_driver::user_selectable_type::TYPED_URLS,
1705 sync_driver::user_selectable_type::EXTENSIONS,
1706 sync_driver::user_selectable_type::APPS,
1707 sync_driver::user_selectable_type::WIFI_CREDENTIAL,
1708 sync_driver::user_selectable_type::PROXY_TABS,
1711 static_assert(36 == syncer::MODEL_TYPE_COUNT,
1712 "custom config histogram must be updated");
1714 if (!sync_everything) {
1715 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1717 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1718 syncer::ModelTypeSet::Iterator it = type_set.First();
1720 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1722 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1723 ++i, it.Inc()) {
1724 const syncer::ModelType type = it.Get();
1725 if (chosen_types.Has(type) &&
1726 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1727 // Selected type has changed - log it.
1728 UMA_HISTOGRAM_ENUMERATION(
1729 "Sync.CustomSync",
1730 user_selectable_types[i],
1731 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1737 #if defined(OS_CHROMEOS)
1738 void ProfileSyncService::RefreshSpareBootstrapToken(
1739 const std::string& passphrase) {
1740 sync_driver::SystemEncryptor encryptor;
1741 syncer::Cryptographer temp_cryptographer(&encryptor);
1742 // The first 2 params (hostname and username) doesn't have any effect here.
1743 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1745 std::string bootstrap_token;
1746 if (!temp_cryptographer.AddKey(key_params)) {
1747 NOTREACHED() << "Failed to add key to cryptographer.";
1749 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1750 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1752 #endif
1754 void ProfileSyncService::OnUserChoseDatatypes(
1755 bool sync_everything,
1756 syncer::ModelTypeSet chosen_types) {
1757 if (!backend_.get() && !HasUnrecoverableError()) {
1758 NOTREACHED();
1759 return;
1762 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1763 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1765 if (directory_data_type_manager_.get())
1766 directory_data_type_manager_->ResetDataTypeErrors();
1767 ChangePreferredDataTypes(chosen_types);
1770 void ProfileSyncService::ChangePreferredDataTypes(
1771 syncer::ModelTypeSet preferred_types) {
1773 DVLOG(1) << "ChangePreferredDataTypes invoked";
1774 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1775 const syncer::ModelTypeSet registered_preferred_types =
1776 Intersection(registered_types, preferred_types);
1777 sync_prefs_.SetPreferredDataTypes(registered_types,
1778 registered_preferred_types);
1780 // Now reconfigure the DTM.
1781 ReconfigureDatatypeManager();
1783 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1784 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1785 // which types should be enabled and when.
1788 syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1789 if (!SyncActive() || !ConfigurationDone())
1790 return syncer::ModelTypeSet();
1791 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1792 const syncer::ModelTypeSet failed_types =
1793 data_type_status_table_.GetFailedTypes();
1794 return Difference(preferred_types, failed_types);
1797 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1798 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1799 const syncer::ModelTypeSet preferred_types =
1800 sync_prefs_.GetPreferredDataTypes(registered_types);
1801 const syncer::ModelTypeSet enforced_types =
1802 Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1803 return Union(preferred_types, enforced_types);
1806 syncer::ModelTypeSet
1807 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1808 const syncer::ModelTypeSet registered_directory_types =
1809 GetRegisteredDirectoryDataTypes();
1810 const syncer::ModelTypeSet preferred_types =
1811 sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1812 const syncer::ModelTypeSet enforced_types =
1813 Intersection(GetDataTypesFromPreferenceProviders(),
1814 registered_directory_types);
1815 return Union(preferred_types, enforced_types);
1818 syncer::ModelTypeSet
1819 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1820 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1823 syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1824 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1825 // we'll need another way to distinguish user-choosable types from
1826 // programmatically-enabled types.
1827 return GetDataTypesFromPreferenceProviders();
1830 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1831 return Union(GetRegisteredDirectoryDataTypes(),
1832 GetRegisteredNonBlockingDataTypes());
1835 syncer::ModelTypeSet
1836 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1837 syncer::ModelTypeSet registered_types;
1838 // The directory_data_type_controllers_ are determined by command-line flags;
1839 // that's effectively what controls the values returned here.
1840 for (DataTypeController::TypeMap::const_iterator it =
1841 directory_data_type_controllers_.begin();
1842 it != directory_data_type_controllers_.end(); ++it) {
1843 registered_types.Put(it->first);
1845 return registered_types;
1848 syncer::ModelTypeSet
1849 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1850 return non_blocking_data_type_manager_.GetRegisteredTypes();
1853 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1854 syncer::PassphraseType passphrase_type = GetPassphraseType();
1855 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1856 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1859 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1860 return backend_->GetPassphraseType();
1863 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1864 return backend_->GetExplicitPassphraseTime();
1867 bool ProfileSyncService::IsCryptographerReady(
1868 const syncer::BaseTransaction* trans) const {
1869 return backend_.get() && backend_->IsCryptographerReady(trans);
1872 void ProfileSyncService::ConfigurePriorityDataTypes() {
1873 const syncer::ModelTypeSet priority_types =
1874 Intersection(GetPreferredDirectoryDataTypes(),
1875 syncer::PriorityUserTypes());
1876 if (!priority_types.Empty()) {
1877 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1878 syncer::CONFIGURE_REASON_RECONFIGURATION :
1879 syncer::CONFIGURE_REASON_NEW_CLIENT;
1880 directory_data_type_manager_->Configure(priority_types, reason);
1884 void ProfileSyncService::ConfigureDataTypeManager() {
1885 // Don't configure datatypes if the setup UI is still on the screen - this
1886 // is to help multi-screen setting UIs (like iOS) where they don't want to
1887 // start syncing data until the user is done configuring encryption options,
1888 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1889 // SetSetupInProgress(false).
1890 if (backend_mode_ == SYNC && startup_controller_->setup_in_progress())
1891 return;
1893 bool restart = false;
1894 if (!directory_data_type_manager_) {
1895 restart = true;
1896 directory_data_type_manager_.reset(
1897 factory_->CreateDataTypeManager(debug_info_listener_,
1898 &directory_data_type_controllers_,
1899 this,
1900 backend_.get(),
1901 this));
1903 // We create the migrator at the same time.
1904 migrator_.reset(
1905 new browser_sync::BackendMigrator(
1906 profile_->GetDebugName(), GetUserShare(),
1907 this, directory_data_type_manager_.get(),
1908 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1909 base::Unretained(this))));
1912 syncer::ModelTypeSet types;
1913 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1914 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1915 types = syncer::BackupTypes();
1916 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1917 } else {
1918 types = GetPreferredDirectoryDataTypes();
1919 if (!HasSyncSetupCompleted()) {
1920 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1921 } else if (restart) {
1922 // Datatype downloads on restart are generally due to newly supported
1923 // datatypes (although it's also possible we're picking up where a failed
1924 // previous configuration left off).
1925 // TODO(sync): consider detecting configuration recovery and setting
1926 // the reason here appropriately.
1927 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1928 } else {
1929 // The user initiated a reconfiguration (either to add or remove types).
1930 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1934 directory_data_type_manager_->Configure(types, reason);
1937 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1938 if (backend_.get() && backend_initialized_) {
1939 return backend_->GetUserShare();
1941 NOTREACHED();
1942 return NULL;
1945 syncer::sessions::SyncSessionSnapshot
1946 ProfileSyncService::GetLastSessionSnapshot() const {
1947 if (backend_)
1948 return backend_->GetLastSessionSnapshot();
1949 return syncer::sessions::SyncSessionSnapshot();
1952 bool ProfileSyncService::HasUnsyncedItems() const {
1953 if (HasSyncingBackend() && backend_initialized_) {
1954 return backend_->HasUnsyncedItems();
1956 NOTREACHED();
1957 return false;
1960 browser_sync::BackendMigrator*
1961 ProfileSyncService::GetBackendMigratorForTest() {
1962 return migrator_.get();
1965 void ProfileSyncService::GetModelSafeRoutingInfo(
1966 syncer::ModelSafeRoutingInfo* out) const {
1967 if (backend_.get() && backend_initialized_) {
1968 backend_->GetModelSafeRoutingInfo(out);
1969 } else {
1970 NOTREACHED();
1974 base::Value* ProfileSyncService::GetTypeStatusMap() const {
1975 scoped_ptr<base::ListValue> result(new base::ListValue());
1977 if (!backend_.get() || !backend_initialized_) {
1978 return result.release();
1981 DataTypeStatusTable::TypeErrorMap error_map =
1982 data_type_status_table_.GetAllErrors();
1983 ModelTypeSet active_types;
1984 ModelTypeSet passive_types;
1985 ModelSafeRoutingInfo routing_info;
1986 backend_->GetModelSafeRoutingInfo(&routing_info);
1987 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1988 it != routing_info.end(); ++it) {
1989 if (it->second == syncer::GROUP_PASSIVE) {
1990 passive_types.Put(it->first);
1991 } else {
1992 active_types.Put(it->first);
1996 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
1997 ModelTypeSet &throttled_types(detailed_status.throttled_types);
1998 ModelTypeSet registered = GetRegisteredDataTypes();
1999 scoped_ptr<base::DictionaryValue> type_status_header(
2000 new base::DictionaryValue());
2002 type_status_header->SetString("name", "Model Type");
2003 type_status_header->SetString("status", "header");
2004 type_status_header->SetString("value", "Group Type");
2005 type_status_header->SetString("num_entries", "Total Entries");
2006 type_status_header->SetString("num_live", "Live Entries");
2007 result->Append(type_status_header.release());
2009 scoped_ptr<base::DictionaryValue> type_status;
2010 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2011 ModelType type = it.Get();
2013 type_status.reset(new base::DictionaryValue());
2014 type_status->SetString("name", ModelTypeToString(type));
2016 if (error_map.find(type) != error_map.end()) {
2017 const syncer::SyncError &error = error_map.find(type)->second;
2018 DCHECK(error.IsSet());
2019 switch (error.GetSeverity()) {
2020 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2021 std::string error_text = "Error: " + error.location().ToString() +
2022 ", " + error.GetMessagePrefix() + error.message();
2023 type_status->SetString("status", "error");
2024 type_status->SetString("value", error_text);
2026 break;
2027 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2028 type_status->SetString("status", "disabled");
2029 type_status->SetString("value", error.message());
2030 break;
2031 default:
2032 NOTREACHED() << "Unexpected error severity.";
2033 break;
2035 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2036 // Show a proxy type in "ok" state unless it is disabled by user.
2037 DCHECK(!throttled_types.Has(type));
2038 type_status->SetString("status", "ok");
2039 type_status->SetString("value", "Passive");
2040 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2041 type_status->SetString("status", "warning");
2042 type_status->SetString("value", "Passive, Throttled");
2043 } else if (passive_types.Has(type)) {
2044 type_status->SetString("status", "warning");
2045 type_status->SetString("value", "Passive");
2046 } else if (throttled_types.Has(type)) {
2047 type_status->SetString("status", "warning");
2048 type_status->SetString("value", "Throttled");
2049 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2050 type_status->SetString("status", "ok");
2051 type_status->SetString("value", "Non-Blocking");
2052 } else if (active_types.Has(type)) {
2053 type_status->SetString("status", "ok");
2054 type_status->SetString("value", "Active: " +
2055 ModelSafeGroupToString(routing_info[type]));
2056 } else {
2057 type_status->SetString("status", "warning");
2058 type_status->SetString("value", "Disabled by User");
2061 int live_count = detailed_status.num_entries_by_type[type] -
2062 detailed_status.num_to_delete_entries_by_type[type];
2063 type_status->SetInteger("num_entries",
2064 detailed_status.num_entries_by_type[type]);
2065 type_status->SetInteger("num_live", live_count);
2067 result->Append(type_status.release());
2069 return result.release();
2072 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2073 if (!backend_)
2074 return;
2075 backend_->DeactivateDataType(type);
2078 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2079 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2080 // If the backend isn't running yet, OnBackendInitialized() will call this
2081 // method again after the backend starts up.
2082 if (cached_passphrase_.empty() || !backend_initialized())
2083 return;
2085 // Backend is up and running, so we can consume the cached passphrase.
2086 std::string passphrase = cached_passphrase_;
2087 cached_passphrase_.clear();
2089 // If we need a passphrase to decrypt data, try the cached passphrase.
2090 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2091 if (SetDecryptionPassphrase(passphrase)) {
2092 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2093 return;
2097 // If we get here, we don't have pending keys (or at least, the passphrase
2098 // doesn't decrypt them) - just try to re-encrypt using the encryption
2099 // passphrase.
2100 if (!IsUsingSecondaryPassphrase())
2101 SetEncryptionPassphrase(passphrase, IMPLICIT);
2104 void ProfileSyncService::RequestAccessToken() {
2105 // Only one active request at a time.
2106 if (access_token_request_ != NULL)
2107 return;
2108 request_access_token_retry_timer_.Stop();
2109 OAuth2TokenService::ScopeSet oauth2_scopes;
2110 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2112 // Invalidate previous token, otherwise token service will return the same
2113 // token again.
2114 const std::string& account_id = signin_->GetAccountIdToUse();
2115 if (!access_token_.empty()) {
2116 oauth2_token_service_->InvalidateToken(
2117 account_id, oauth2_scopes, access_token_);
2120 access_token_.clear();
2122 token_request_time_ = base::Time::Now();
2123 token_receive_time_ = base::Time();
2124 next_token_request_time_ = base::Time();
2125 access_token_request_ =
2126 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2129 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2130 PassphraseType type) {
2131 // This should only be called when the backend has been initialized.
2132 DCHECK(backend_initialized());
2133 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2134 "Data is already encrypted using an explicit passphrase";
2135 DCHECK(!(type == EXPLICIT &&
2136 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2137 "Can not set explicit passphrase when decryption is needed.";
2139 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2140 << " passphrase for encryption.";
2141 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2142 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2143 // keys. Hence, as long as we're not trying to do an invalid passphrase
2144 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2145 // will succeed. If for some reason a new encryption key arrives via
2146 // sync later, the SBH will trigger another OnPassphraseRequired().
2147 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2148 NotifyObservers();
2150 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2153 bool ProfileSyncService::SetDecryptionPassphrase(
2154 const std::string& passphrase) {
2155 if (IsPassphraseRequired()) {
2156 DVLOG(1) << "Setting passphrase for decryption.";
2157 bool result = backend_->SetDecryptionPassphrase(passphrase);
2158 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result);
2159 return result;
2160 } else {
2161 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2162 "IsPassphraseRequired() is false.";
2163 return false;
2167 bool ProfileSyncService::EncryptEverythingAllowed() const {
2168 return encrypt_everything_allowed_;
2171 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2172 DCHECK(allowed || !backend_initialized() || !EncryptEverythingEnabled());
2173 encrypt_everything_allowed_ = allowed;
2176 void ProfileSyncService::EnableEncryptEverything() {
2177 DCHECK(EncryptEverythingAllowed());
2179 // Tests override backend_initialized() to always return true, so we
2180 // must check that instead of |backend_initialized_|.
2181 // TODO(akalin): Fix the above. :/
2182 DCHECK(backend_initialized());
2183 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2184 // problems around cancelling encryption in the background (crbug.com/119649).
2185 if (!encrypt_everything_)
2186 encryption_pending_ = true;
2189 bool ProfileSyncService::encryption_pending() const {
2190 // We may be called during the setup process before we're
2191 // initialized (via IsEncryptedDatatypeEnabled and
2192 // IsPassphraseRequiredForDecryption).
2193 return encryption_pending_;
2196 bool ProfileSyncService::EncryptEverythingEnabled() const {
2197 DCHECK(backend_initialized_);
2198 return encrypt_everything_ || encryption_pending_;
2201 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2202 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2203 // We may be called during the setup process before we're
2204 // initialized. In this case, we default to the sensitive types.
2205 return encrypted_types_;
2208 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2209 if (is_sync_managed) {
2210 DisableForUser();
2211 } else {
2212 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2213 startup_controller_->TryStart();
2217 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2218 const std::string& username,
2219 const std::string& password) {
2220 if (!sync_prefs_.IsStartSuppressed() && !password.empty()) {
2221 cached_passphrase_ = password;
2222 // Try to consume the passphrase we just cached. If the sync backend
2223 // is not running yet, the passphrase will remain cached until the
2224 // backend starts up.
2225 ConsumeCachedPassphraseIfPossible();
2227 #if defined(OS_CHROMEOS)
2228 RefreshSpareBootstrapToken(password);
2229 #endif
2230 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE) {
2231 // Track the fact that we're still waiting for auth to complete.
2232 is_auth_in_progress_ = true;
2236 void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2237 const std::string& username) {
2238 sync_disabled_by_admin_ = false;
2239 DisableForUser();
2241 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2242 need_backup_ = true;
2243 backup_finished_ = false;
2247 void ProfileSyncService::AddObserver(
2248 sync_driver::SyncServiceObserver* observer) {
2249 observers_.AddObserver(observer);
2252 void ProfileSyncService::RemoveObserver(
2253 sync_driver::SyncServiceObserver* observer) {
2254 observers_.RemoveObserver(observer);
2257 void ProfileSyncService::AddProtocolEventObserver(
2258 browser_sync::ProtocolEventObserver* observer) {
2259 protocol_event_observers_.AddObserver(observer);
2260 if (HasSyncingBackend()) {
2261 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2265 void ProfileSyncService::RemoveProtocolEventObserver(
2266 browser_sync::ProtocolEventObserver* observer) {
2267 protocol_event_observers_.RemoveObserver(observer);
2268 if (HasSyncingBackend() &&
2269 !protocol_event_observers_.might_have_observers()) {
2270 backend_->DisableProtocolEventForwarding();
2274 void ProfileSyncService::AddTypeDebugInfoObserver(
2275 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2276 type_debug_info_observers_.AddObserver(type_debug_info_observer);
2277 if (type_debug_info_observers_.might_have_observers() &&
2278 backend_initialized_) {
2279 backend_->EnableDirectoryTypeDebugInfoForwarding();
2283 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2284 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2285 type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2286 if (!type_debug_info_observers_.might_have_observers() &&
2287 backend_initialized_) {
2288 backend_->DisableDirectoryTypeDebugInfoForwarding();
2292 void ProfileSyncService::AddPreferenceProvider(
2293 SyncTypePreferenceProvider* provider) {
2294 DCHECK(!HasPreferenceProvider(provider))
2295 << "Providers may only be added once!";
2296 preference_providers_.insert(provider);
2299 void ProfileSyncService::RemovePreferenceProvider(
2300 SyncTypePreferenceProvider* provider) {
2301 DCHECK(HasPreferenceProvider(provider))
2302 << "Only providers that have been added before can be removed!";
2303 preference_providers_.erase(provider);
2306 bool ProfileSyncService::HasPreferenceProvider(
2307 SyncTypePreferenceProvider* provider) const {
2308 return preference_providers_.count(provider) > 0;
2311 namespace {
2313 class GetAllNodesRequestHelper
2314 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2315 public:
2316 GetAllNodesRequestHelper(
2317 syncer::ModelTypeSet requested_types,
2318 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2320 void OnReceivedNodesForTypes(
2321 const std::vector<syncer::ModelType>& types,
2322 ScopedVector<base::ListValue> scoped_node_lists);
2324 private:
2325 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2326 virtual ~GetAllNodesRequestHelper();
2328 scoped_ptr<base::ListValue> result_accumulator_;
2330 syncer::ModelTypeSet awaiting_types_;
2331 base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2334 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2335 syncer::ModelTypeSet requested_types,
2336 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2337 : result_accumulator_(new base::ListValue()),
2338 awaiting_types_(requested_types),
2339 callback_(callback) {}
2341 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2342 if (!awaiting_types_.Empty()) {
2343 DLOG(WARNING)
2344 << "GetAllNodesRequest deleted before request was fulfilled. "
2345 << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2349 // Called when the set of nodes for a type or set of types has been returned.
2351 // The nodes for several types can be returned at the same time by specifying
2352 // their types in the |types| array, and putting their results at the
2353 // correspnding indices in the |scoped_node_lists|.
2354 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2355 const std::vector<syncer::ModelType>& types,
2356 ScopedVector<base::ListValue> scoped_node_lists) {
2357 DCHECK_EQ(types.size(), scoped_node_lists.size());
2359 // Take unsafe ownership of the node list.
2360 std::vector<base::ListValue*> node_lists;
2361 scoped_node_lists.release(&node_lists);
2363 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2364 const ModelType type = types[i];
2365 base::ListValue* node_list = node_lists[i];
2367 // Add these results to our list.
2368 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2369 type_dict->SetString("type", ModelTypeToString(type));
2370 type_dict->Set("nodes", node_list);
2371 result_accumulator_->Append(type_dict.release());
2373 // Remember that this part of the request is satisfied.
2374 awaiting_types_.Remove(type);
2377 if (awaiting_types_.Empty()) {
2378 callback_.Run(result_accumulator_.Pass());
2379 callback_.Reset();
2383 } // namespace
2385 void ProfileSyncService::GetAllNodes(
2386 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2387 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2388 directory_types.PutAll(syncer::ControlTypes());
2389 scoped_refptr<GetAllNodesRequestHelper> helper =
2390 new GetAllNodesRequestHelper(directory_types, callback);
2392 if (!backend_initialized_) {
2393 // If there's no backend available to fulfill the request, handle it here.
2394 ScopedVector<base::ListValue> empty_results;
2395 std::vector<ModelType> type_vector;
2396 for (ModelTypeSet::Iterator it = directory_types.First();
2397 it.Good(); it.Inc()) {
2398 type_vector.push_back(it.Get());
2399 empty_results.push_back(new base::ListValue());
2401 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2402 } else {
2403 backend_->GetAllNodesForTypes(
2404 directory_types,
2405 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2409 bool ProfileSyncService::HasObserver(
2410 const sync_driver::SyncServiceObserver* observer) const {
2411 return observers_.HasObserver(observer);
2414 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2415 return sync_js_controller_.AsWeakPtr();
2418 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2419 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2422 // static
2423 bool ProfileSyncService::IsSyncAllowedByFlag() {
2424 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2425 switches::kDisableSync);
2428 bool ProfileSyncService::IsManaged() const {
2429 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2432 void ProfileSyncService::StopAndSuppress() {
2433 sync_prefs_.SetStartSuppressed(true);
2434 if (HasSyncingBackend()) {
2435 backend_->UnregisterInvalidationIds();
2437 ShutdownImpl(syncer::STOP_SYNC);
2440 bool ProfileSyncService::IsStartSuppressed() const {
2441 return sync_prefs_.IsStartSuppressed();
2444 SigninManagerBase* ProfileSyncService::signin() const {
2445 if (!signin_)
2446 return NULL;
2447 return signin_->GetOriginal();
2450 void ProfileSyncService::UnsuppressAndStart() {
2451 DCHECK(profile_);
2452 sync_prefs_.SetStartSuppressed(false);
2453 DCHECK(!signin_.get() || signin_->GetOriginal()->IsAuthenticated());
2454 startup_controller_->TryStart();
2457 void ProfileSyncService::ReconfigureDatatypeManager() {
2458 // If we haven't initialized yet, don't configure the DTM as it could cause
2459 // association to start before a Directory has even been created.
2460 if (backend_initialized_) {
2461 DCHECK(backend_.get());
2462 ConfigureDataTypeManager();
2463 } else if (HasUnrecoverableError()) {
2464 // There is nothing more to configure. So inform the listeners,
2465 NotifyObservers();
2467 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2468 << "Unrecoverable error.";
2469 } else {
2470 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2471 << "initialized";
2475 syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2476 const {
2477 syncer::ModelTypeSet types;
2478 for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2479 preference_providers_.begin();
2480 it != preference_providers_.end();
2481 ++it) {
2482 types.PutAll((*it)->GetPreferredDataTypes());
2484 return types;
2487 const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2488 const {
2489 return data_type_status_table_;
2492 void ProfileSyncService::OnInternalUnrecoverableError(
2493 const tracked_objects::Location& from_here,
2494 const std::string& message,
2495 bool delete_sync_database,
2496 UnrecoverableErrorReason reason) {
2497 DCHECK(!HasUnrecoverableError());
2498 unrecoverable_error_reason_ = reason;
2499 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2502 syncer::SyncManagerFactory::MANAGER_TYPE
2503 ProfileSyncService::GetManagerType() const {
2504 switch (backend_mode_) {
2505 case SYNC:
2506 return syncer::SyncManagerFactory::NORMAL;
2507 case BACKUP:
2508 return syncer::SyncManagerFactory::BACKUP;
2509 case ROLLBACK:
2510 return syncer::SyncManagerFactory::ROLLBACK;
2511 case IDLE:
2512 NOTREACHED();
2514 return syncer::SyncManagerFactory::NORMAL;
2517 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2518 return request_access_token_retry_timer_.IsRunning();
2521 std::string ProfileSyncService::GetAccessTokenForTest() const {
2522 return access_token_;
2525 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2526 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2529 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2530 return sessions_sync_manager_.get();
2533 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2534 return device_info_sync_service_.get();
2537 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2538 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED),
2539 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2540 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2542 ProfileSyncService::SyncTokenStatus
2543 ProfileSyncService::GetSyncTokenStatus() const {
2544 SyncTokenStatus status;
2545 status.connection_status_update_time = connection_status_update_time_;
2546 status.connection_status = connection_status_;
2547 status.token_request_time = token_request_time_;
2548 status.token_receive_time = token_receive_time_;
2549 status.last_get_token_error = last_get_token_error_;
2550 if (request_access_token_retry_timer_.IsRunning())
2551 status.next_token_request_time = next_token_request_time_;
2552 return status;
2555 void ProfileSyncService::OverrideNetworkResourcesForTest(
2556 scoped_ptr<syncer::NetworkResources> network_resources) {
2557 network_resources_ = network_resources.Pass();
2560 bool ProfileSyncService::HasSyncingBackend() const {
2561 return backend_mode_ != SYNC ? false : backend_ != NULL;
2564 void ProfileSyncService::UpdateFirstSyncTimePref() {
2565 if (signin_->GetAccountIdToUse().empty()) {
2566 // Clear if user's not signed in and rollback is done.
2567 if (backend_mode_ != ROLLBACK)
2568 sync_prefs_.ClearFirstSyncTime();
2569 } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2570 backend_mode_ == SYNC) {
2571 // Set if not set before and it's syncing now.
2572 sync_prefs_.SetFirstSyncTime(base::Time::Now());
2576 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2577 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2578 if (first_sync_time.is_null())
2579 return;
2581 clear_browsing_data_.Run(browsing_data_remover_observer_,
2582 profile_,
2583 first_sync_time,
2584 base::Time::Now());
2587 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2588 BrowsingDataRemover::Observer* observer) {
2589 browsing_data_remover_observer_ = observer;
2592 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2593 base::Callback<void(BrowsingDataRemover::Observer* observer,
2594 Profile*,
2595 base::Time,
2596 base::Time)> c) {
2597 clear_browsing_data_ = c;
2600 GURL ProfileSyncService::GetSyncServiceURL(
2601 const base::CommandLine& command_line) {
2602 // By default, dev, canary, and unbranded Chromium users will go to the
2603 // development servers. Development servers have more features than standard
2604 // sync servers. Users with officially-branded Chrome stable and beta builds
2605 // will go to the standard sync servers.
2606 GURL result(kDevServerUrl);
2608 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
2609 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
2610 channel == chrome::VersionInfo::CHANNEL_BETA) {
2611 result = GURL(kSyncServerUrl);
2614 // Override the sync server URL from the command-line, if sync server
2615 // command-line argument exists.
2616 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
2617 std::string value(command_line.GetSwitchValueASCII(
2618 switches::kSyncServiceURL));
2619 if (!value.empty()) {
2620 GURL custom_sync_url(value);
2621 if (custom_sync_url.is_valid()) {
2622 result = custom_sync_url;
2623 } else {
2624 LOG(WARNING) << "The following sync URL specified at the command-line "
2625 << "is invalid: " << value;
2629 return result;
2632 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2633 DCHECK_EQ(backend_mode_, SYNC);
2635 #if defined(ENABLE_PRE_SYNC_BACKUP)
2636 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
2637 // Check backup once a day.
2638 if (!last_backup_time_ &&
2639 (last_synced_time.is_null() ||
2640 base::Time::Now() - last_synced_time >=
2641 base::TimeDelta::FromDays(1))) {
2642 // If sync thread is set, need to serialize check on sync thread after
2643 // closing backup DB.
2644 if (sync_thread_) {
2645 sync_thread_->message_loop_proxy()->PostTask(
2646 FROM_HERE,
2647 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2648 profile_->GetPath().Append(kSyncBackupDataFolderName),
2649 base::ThreadTaskRunnerHandle::Get(),
2650 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2651 weak_factory_.GetWeakPtr())));
2652 } else {
2653 content::BrowserThread::PostTask(
2654 content::BrowserThread::FILE, FROM_HERE,
2655 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2656 profile_->GetPath().Append(kSyncBackupDataFolderName),
2657 base::ThreadTaskRunnerHandle::Get(),
2658 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2659 weak_factory_.GetWeakPtr())));
2662 #endif
2665 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2666 last_backup_time_.reset(new base::Time(backup_time));
2668 DCHECK(device_info_sync_service_);
2669 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2672 void ProfileSyncService::TryStartSyncAfterBackup() {
2673 startup_controller_->Reset(GetRegisteredDataTypes());
2674 startup_controller_->TryStart();
2677 void ProfileSyncService::CleanUpBackup() {
2678 sync_prefs_.ClearFirstSyncTime();
2679 profile_->GetIOTaskRunner()->PostTask(
2680 FROM_HERE,
2681 base::Bind(base::IgnoreResult(base::DeleteFile),
2682 profile_->GetPath().Append(kSyncBackupDataFolderName),
2683 true));
2686 bool ProfileSyncService::NeedBackup() const {
2687 return need_backup_;
2690 base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2691 return device_info_sync_service_->GetLocalDeviceBackupTime();
2694 void ProfileSyncService::FlushDirectory() const {
2695 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2696 // If sync is not initialized yet, we fail silently.
2697 if (backend_initialized_)
2698 backend_->FlushDirectory();
2701 base::FilePath ProfileSyncService::GetDirectoryPathForTest() const {
2702 return directory_path_;
2705 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2706 if (sync_thread_) {
2707 return sync_thread_->message_loop();
2708 } else if (backend_) {
2709 return backend_->GetSyncLoopForTesting();
2710 } else {
2711 return NULL;
2715 void ProfileSyncService::RemoveClientFromServer() const {
2716 if (!backend_initialized_) return;
2717 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
2718 std::string birthday;
2719 syncer::UserShare* user_share = GetUserShare();
2720 if (user_share && user_share->directory.get()) {
2721 birthday = user_share->directory->store_birthday();
2723 if (!access_token_.empty() && !cache_guid.empty() && !birthday.empty()) {
2724 sync_stopped_reporter_->ReportSyncStopped(
2725 access_token_, cache_guid, birthday);
2729 void ProfileSyncService::OnMemoryPressure(
2730 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
2731 if (memory_pressure_level ==
2732 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2733 sync_prefs_.SetMemoryPressureWarningCount(
2734 sync_prefs_.GetMemoryPressureWarningCount() + 1);
2738 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2739 int warning_received = sync_prefs_.GetMemoryPressureWarningCount();
2741 if (-1 != warning_received) {
2742 // -1 means it is new client.
2743 if (!sync_prefs_.DidSyncShutdownCleanly()) {
2744 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2745 warning_received);
2746 } else {
2747 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2748 warning_received);
2751 sync_prefs_.SetMemoryPressureWarningCount(0);
2752 // Will set to true during a clean shutdown, so crash or something else will
2753 // remain this as false.
2754 sync_prefs_.SetCleanShutdown(false);