Changes for start_with_ext Telemetry test to work on Windows.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blobc505be876d5a7ca7f10149dc41e48a2a33257b8a
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/metrics/histogram.h"
21 #include "base/profiler/scoped_tracker.h"
22 #include "base/single_thread_task_runner.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/thread_task_runner_handle.h"
26 #include "base/threading/thread_restrictions.h"
27 #include "build/build_config.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/browsing_data/browsing_data_helper.h"
30 #include "chrome/browser/chrome_notification_types.h"
31 #include "chrome/browser/defaults.h"
32 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
33 #include "chrome/browser/net/chrome_cookie_notification_details.h"
34 #include "chrome/browser/password_manager/password_store_factory.h"
35 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
36 #include "chrome/browser/prefs/pref_service_syncable.h"
37 #include "chrome/browser/profiles/profile.h"
38 #include "chrome/browser/signin/about_signin_internals_factory.h"
39 #include "chrome/browser/signin/chrome_signin_client_factory.h"
40 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
41 #include "chrome/browser/signin/signin_manager_factory.h"
42 #include "chrome/browser/sync/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/pref_names.h"
62 #include "chrome/common/sync_util.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/impl/profile_invalidation_provider.h"
67 #include "components/invalidation/public/invalidation_service.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 kSyncUnrecoverableErrorHistogram[] =
131 "Sync.UnrecoverableErrors";
133 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
134 // Number of initial errors (in sequence) to ignore before applying
135 // exponential back-off rules.
138 // Initial delay for exponential back-off in ms.
139 2000,
141 // Factor by which the waiting time will be multiplied.
144 // Fuzzing percentage. ex: 10% will spread requests randomly
145 // between 90%-100% of the calculated time.
146 0.2, // 20%
148 // Maximum amount of time we are willing to delay our request in ms.
149 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
150 // RequestAccessToken on connection state change after backoff
151 1000 * 3600 * 4, // 4 hours.
153 // Time to keep an entry from being discarded even when it
154 // has no significant state, -1 to never discard.
157 // Don't use initial delay unless the last request was an error.
158 false,
161 static const base::FilePath::CharType kSyncDataFolderName[] =
162 FILE_PATH_LITERAL("Sync Data");
164 static const base::FilePath::CharType kSyncBackupDataFolderName[] =
165 FILE_PATH_LITERAL("Sync Data Backup");
167 namespace {
169 void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
170 Profile* profile,
171 base::Time start,
172 base::Time end) {
173 // BrowsingDataRemover deletes itself when it's done.
174 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
175 profile, start, end);
176 if (observer)
177 remover->AddObserver(observer);
178 remover->Remove(BrowsingDataRemover::REMOVE_ALL,
179 BrowsingDataHelper::ALL);
181 scoped_refptr<password_manager::PasswordStore> password =
182 PasswordStoreFactory::GetForProfile(profile,
183 ServiceAccessType::EXPLICIT_ACCESS);
184 password->RemoveLoginsSyncedBetween(start, end);
187 // Perform the actual sync data folder deletion.
188 // This should only be called on the sync thread.
189 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
190 if (base::DirectoryExists(directory_path)) {
191 if (!base::DeleteFile(directory_path, true))
192 LOG(DFATAL) << "Could not delete the Sync Data folder.";
196 } // anonymous namespace
198 bool ShouldShowActionOnUI(
199 const syncer::SyncProtocolError& error) {
200 return (error.action != syncer::UNKNOWN_ACTION &&
201 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
202 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
205 ProfileSyncService::ProfileSyncService(
206 scoped_ptr<ProfileSyncComponentsFactory> factory,
207 Profile* profile,
208 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
209 ProfileOAuth2TokenService* oauth2_token_service,
210 ProfileSyncServiceStartBehavior start_behavior)
211 : OAuth2TokenService::Consumer("sync"),
212 last_auth_error_(AuthError::AuthErrorNone()),
213 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
214 factory_(factory.Pass()),
215 profile_(profile),
216 sync_prefs_(profile_->GetPrefs()),
217 sync_service_url_(
218 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
219 is_first_time_sync_configure_(false),
220 backend_initialized_(false),
221 sync_disabled_by_admin_(false),
222 is_auth_in_progress_(false),
223 signin_(signin_wrapper.Pass()),
224 unrecoverable_error_reason_(ERROR_REASON_UNSET),
225 expect_sync_configuration_aborted_(false),
226 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
227 encrypt_everything_allowed_(true),
228 encrypt_everything_(false),
229 encryption_pending_(false),
230 configure_status_(DataTypeManager::UNKNOWN),
231 oauth2_token_service_(oauth2_token_service),
232 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
233 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
234 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
235 network_resources_(new syncer::HttpBridgeNetworkResources),
236 backend_mode_(IDLE),
237 need_backup_(false),
238 backup_finished_(false),
239 clear_browsing_data_(base::Bind(&ClearBrowsingData)),
240 browsing_data_remover_observer_(NULL),
241 sync_stopped_reporter_(
242 new browser_sync::SyncStoppedReporter(
243 sync_service_url_,
244 profile_->GetRequestContext(),
245 browser_sync::SyncStoppedReporter::ResultCallback())),
246 weak_factory_(this),
247 startup_controller_weak_factory_(this) {
248 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
249 DCHECK(profile);
250 startup_controller_.reset(new browser_sync::StartupController(
251 start_behavior,
252 oauth2_token_service,
253 &sync_prefs_,
254 signin_.get(),
255 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
256 startup_controller_weak_factory_.GetWeakPtr(),
257 SYNC)));
258 backup_rollback_controller_.reset(new browser_sync::BackupRollbackController(
259 &sync_prefs_,
260 signin_.get(),
261 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
262 startup_controller_weak_factory_.GetWeakPtr(),
263 BACKUP),
264 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
265 startup_controller_weak_factory_.GetWeakPtr(),
266 ROLLBACK)));
267 syncer::SyncableService::StartSyncFlare flare(
268 sync_start_util::GetFlareForSyncableService(profile->GetPath()));
269 scoped_ptr<browser_sync::LocalSessionEventRouter> router(
270 new NotificationServiceSessionsRouter(profile, flare));
272 DCHECK(factory_.get());
273 local_device_ = factory_->CreateLocalDeviceInfoProvider();
274 sessions_sync_manager_.reset(
275 new SessionsSyncManager(profile, local_device_.get(), router.Pass()));
276 device_info_sync_service_.reset(
277 new DeviceInfoSyncService(local_device_.get()));
280 ProfileSyncService::~ProfileSyncService() {
281 sync_prefs_.RemoveSyncPrefObserver(this);
282 // Shutdown() should have been called before destruction.
283 CHECK(!backend_initialized_);
286 bool ProfileSyncService::CanSyncStart() const {
287 return IsSyncAllowed() && IsSyncRequested() && IsSignedIn();
290 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
291 if (!oauth2_token_service_)
292 return false;
294 return oauth2_token_service_->RefreshTokenIsAvailable(
295 signin_->GetAccountIdToUse());
298 void ProfileSyncService::Initialize() {
299 // We clear this here (vs Shutdown) because we want to remember that an error
300 // happened on shutdown so we can display details (message, location) about it
301 // in about:sync.
302 ClearStaleErrors();
304 sync_prefs_.AddSyncPrefObserver(this);
306 // If sync isn't allowed, the only thing to do is to turn it off.
307 if (!IsSyncAllowed()) {
308 RequestStop(CLEAR_DATA);
309 return;
312 RegisterAuthNotifications();
314 if (!HasSyncSetupCompleted() || !IsSignedIn()) {
315 // Clean up in case of previous crash / setup abort / signout.
316 StopImpl(CLEAR_DATA);
319 TrySyncDatatypePrefRecovery();
321 #if defined(OS_CHROMEOS)
322 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
323 if (bootstrap_token.empty()) {
324 sync_prefs_.SetEncryptionBootstrapToken(
325 sync_prefs_.GetSpareBootstrapToken());
327 #endif
329 #if !defined(OS_ANDROID)
330 DCHECK(sync_error_controller_ == NULL)
331 << "Initialize() called more than once.";
332 sync_error_controller_.reset(new SyncErrorController(this));
333 AddObserver(sync_error_controller_.get());
334 #endif
336 bool running_rollback = false;
337 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
338 // Backup is needed if user's not signed in or signed in but previous
339 // backup didn't finish, i.e. backend didn't switch from backup to sync.
340 need_backup_ = !IsSignedIn() || sync_prefs_.GetFirstSyncTime().is_null();
342 // Try to resume rollback if it didn't finish in last session.
343 running_rollback = backup_rollback_controller_->StartRollback();
344 } else {
345 need_backup_ = false;
348 #if defined(ENABLE_PRE_SYNC_BACKUP)
349 if (!running_rollback && !IsSignedIn()) {
350 CleanUpBackup();
352 #else
353 DCHECK(!running_rollback);
354 #endif
356 memory_pressure_listener_.reset(new base::MemoryPressureListener(base::Bind(
357 &ProfileSyncService::OnMemoryPressure, weak_factory_.GetWeakPtr())));
358 startup_controller_->Reset(GetRegisteredDataTypes());
359 startup_controller_->TryStart();
362 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
363 DCHECK(!backend_initialized());
364 if (!HasSyncSetupCompleted())
365 return;
367 // There was a bug where OnUserChoseDatatypes was not properly called on
368 // configuration (see crbug.com/154940). We detect this by checking whether
369 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
370 // completed, it means sync was not properly configured, so we manually
371 // set kSyncKeepEverythingSynced.
372 PrefService* const pref_service = profile_->GetPrefs();
373 if (!pref_service)
374 return;
375 if (GetPreferredDataTypes().Size() > 1)
376 return;
378 const PrefService::Preference* keep_everything_synced =
379 pref_service->FindPreference(
380 sync_driver::prefs::kSyncKeepEverythingSynced);
381 // This will be false if the preference was properly set or if it's controlled
382 // by policy.
383 if (!keep_everything_synced->IsDefaultValue())
384 return;
386 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
387 // types now, before we configure.
388 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
389 sync_prefs_.SetKeepEverythingSynced(true);
390 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
393 void ProfileSyncService::StartSyncingWithServer() {
394 if (backend_)
395 backend_->StartSyncingWithServer();
398 void ProfileSyncService::RegisterAuthNotifications() {
399 oauth2_token_service_->AddObserver(this);
400 if (signin())
401 signin()->AddObserver(this);
404 void ProfileSyncService::UnregisterAuthNotifications() {
405 if (signin())
406 signin()->RemoveObserver(this);
407 oauth2_token_service_->RemoveObserver(this);
410 void ProfileSyncService::RegisterDataTypeController(
411 DataTypeController* data_type_controller) {
412 DCHECK_EQ(
413 directory_data_type_controllers_.count(data_type_controller->type()),
414 0U);
415 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
416 data_type_controller->type()));
417 directory_data_type_controllers_[data_type_controller->type()] =
418 data_type_controller;
421 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
422 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
423 << "Duplicate registration of type " << ModelTypeToString(type);
425 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
426 // fixed and we have some way of telling whether or not this type should be
427 // enabled.
428 non_blocking_data_type_manager_.RegisterType(type, false);
431 void ProfileSyncService::InitializeNonBlockingType(
432 syncer::ModelType type,
433 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
434 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) {
435 non_blocking_data_type_manager_.InitializeType(
436 type, task_runner, type_sync_proxy);
439 bool ProfileSyncService::IsDataTypeControllerRunning(
440 syncer::ModelType type) const {
441 DataTypeController::TypeMap::const_iterator iter =
442 directory_data_type_controllers_.find(type);
443 if (iter == directory_data_type_controllers_.end()) {
444 return false;
446 return iter->second->state() == DataTypeController::RUNNING;
449 sync_driver::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
450 if (!IsDataTypeControllerRunning(syncer::SESSIONS))
451 return NULL;
452 return sessions_sync_manager_.get();
455 browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
456 return sessions_sync_manager_->GetFaviconCache();
459 browser_sync::SyncedWindowDelegatesGetter*
460 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
461 return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
464 sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
465 const {
466 return device_info_sync_service_.get();
469 sync_driver::LocalDeviceInfoProvider*
470 ProfileSyncService::GetLocalDeviceInfoProvider() {
471 return local_device_.get();
474 void ProfileSyncService::GetDataTypeControllerStates(
475 DataTypeController::StateMap* state_map) const {
476 for (DataTypeController::TypeMap::const_iterator iter =
477 directory_data_type_controllers_.begin();
478 iter != directory_data_type_controllers_.end();
479 ++iter)
480 (*state_map)[iter->first] = iter->second.get()->state();
483 SyncCredentials ProfileSyncService::GetCredentials() {
484 SyncCredentials credentials;
485 if (backend_mode_ == SYNC) {
486 credentials.email = signin_->GetEffectiveUsername();
487 DCHECK(!credentials.email.empty());
488 credentials.sync_token = access_token_;
490 if (credentials.sync_token.empty())
491 credentials.sync_token = "credentials_lost";
493 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
496 return credentials;
499 bool ProfileSyncService::ShouldDeleteSyncFolder() {
500 switch (backend_mode_) {
501 case SYNC:
502 return !HasSyncSetupCompleted();
503 case BACKUP:
504 return true;
505 case ROLLBACK:
506 return false;
507 case IDLE:
508 NOTREACHED();
509 return true;
511 return true;
514 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
515 if (!backend_) {
516 NOTREACHED();
517 return;
520 SyncCredentials credentials = GetCredentials();
522 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
523 profile_->GetRequestContext());
525 if (backend_mode_ == SYNC && delete_stale_data)
526 ClearStaleErrors();
528 scoped_ptr<syncer::UnrecoverableErrorHandler>
529 backend_unrecoverable_error_handler(
530 new browser_sync::BackendUnrecoverableErrorHandler(
531 MakeWeakHandle(weak_factory_.GetWeakPtr())));
533 backend_->Initialize(this, sync_thread_.Pass(), GetJsEventHandler(),
534 sync_service_url_, credentials, delete_stale_data,
535 scoped_ptr<syncer::SyncManagerFactory>(
536 new syncer::SyncManagerFactory(GetManagerType()))
537 .Pass(),
538 backend_unrecoverable_error_handler.Pass(),
539 base::Bind(browser_sync::ChromeReportUnrecoverableError),
540 network_resources_.get(), saved_nigori_state_.Pass());
543 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
544 if (encryption_pending())
545 return true;
546 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
547 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
548 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
549 return !Intersection(preferred_types, encrypted_types).Empty();
552 void ProfileSyncService::OnProtocolEvent(
553 const syncer::ProtocolEvent& event) {
554 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
555 protocol_event_observers_,
556 OnProtocolEvent(event));
559 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
560 syncer::ModelType type,
561 const syncer::CommitCounters& counters) {
562 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
563 type_debug_info_observers_,
564 OnCommitCountersUpdated(type, counters));
567 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
568 syncer::ModelType type,
569 const syncer::UpdateCounters& counters) {
570 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
571 type_debug_info_observers_,
572 OnUpdateCountersUpdated(type, counters));
575 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
576 syncer::ModelType type,
577 const syncer::StatusCounters& counters) {
578 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
579 type_debug_info_observers_,
580 OnStatusCountersUpdated(type, counters));
583 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
584 syncer::ModelType type) {
585 DCHECK(syncer::UserTypes().Has(type));
586 if (backend_.get()) {
587 DVLOG(1) << "A data type requested sync startup, but it looks like "
588 "something else beat it to the punch.";
589 return;
592 if (!GetPreferredDataTypes().Has(type)) {
593 // We can get here as datatype SyncableServices are typically wired up
594 // to the native datatype even if sync isn't enabled.
595 DVLOG(1) << "Dropping sync startup request because type "
596 << syncer::ModelTypeToString(type) << "not enabled.";
597 return;
600 startup_controller_->OnDataTypeRequestsSyncStartup(type);
603 void ProfileSyncService::StartUpSlowBackendComponents(
604 ProfileSyncService::BackendMode mode) {
605 DCHECK_NE(IDLE, mode);
606 if (backend_mode_ == mode) {
607 return;
610 // Backend mode transition rules:
611 // * can transit from IDLE to any other non-IDLE mode.
612 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
613 // be explicitly shut down before backup/rollback starts.
614 // * can not transit out of ROLLBACK mode until rollback is finished
615 // (successfully or unsuccessfully).
616 // * can not transit out of BACKUP mode until backup is finished
617 // (successfully or unsuccessfully).
618 // * if backup is needed, can only transit to SYNC if backup is finished,
620 if (backend_mode_ == SYNC) {
621 LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
622 return;
625 if (backend_mode_ == ROLLBACK ||
626 (backend_mode_ == BACKUP && !backup_finished_)) {
627 // Wait for rollback/backup to finish before start new backend.
628 return;
631 if (mode == SYNC && NeedBackup() && !backup_finished_) {
632 if (backend_mode_ != BACKUP)
633 backup_rollback_controller_->StartBackup();
634 return;
637 DVLOG(1) << "Start backend mode: " << mode;
639 if (backend_) {
640 if (mode == SYNC)
641 ShutdownImpl(syncer::SWITCH_MODE_SYNC);
642 else
643 ShutdownImpl(syncer::STOP_SYNC);
646 backend_mode_ = mode;
648 if (backend_mode_ == BACKUP)
649 backup_start_time_ = base::Time::Now();
651 if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
652 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
653 base::Time::Now() - backup_start_time_);
654 backup_start_time_ = base::Time();
657 if (backend_mode_ == ROLLBACK)
658 ClearBrowsingDataSinceFirstSync();
659 else if (backend_mode_ == SYNC)
660 CheckSyncBackupIfNeeded();
662 base::FilePath sync_folder = backend_mode_ == SYNC ?
663 base::FilePath(kSyncDataFolderName) :
664 base::FilePath(kSyncBackupDataFolderName);
666 invalidation::InvalidationService* invalidator = NULL;
667 if (backend_mode_ == SYNC) {
668 invalidation::ProfileInvalidationProvider* provider =
669 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
670 profile_);
671 if (provider)
672 invalidator = provider->GetInvalidationService();
675 directory_path_ = profile_->GetPath().Append(sync_folder);
677 backend_.reset(
678 factory_->CreateSyncBackendHost(
679 profile_->GetDebugName(),
680 profile_,
681 invalidator,
682 sync_prefs_.AsWeakPtr(),
683 sync_folder));
685 // Initialize the backend. Every time we start up a new SyncBackendHost,
686 // we'll want to start from a fresh SyncDB, so delete any old one that might
687 // be there.
688 InitializeBackend(ShouldDeleteSyncFolder());
690 UpdateFirstSyncTimePref();
692 ReportPreviousSessionMemoryWarningCount();
695 void ProfileSyncService::OnGetTokenSuccess(
696 const OAuth2TokenService::Request* request,
697 const std::string& access_token,
698 const base::Time& expiration_time) {
699 DCHECK_EQ(access_token_request_, request);
700 access_token_request_.reset();
701 access_token_ = access_token;
702 token_receive_time_ = base::Time::Now();
703 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
705 if (sync_prefs_.SyncHasAuthError()) {
706 sync_prefs_.SetSyncAuthError(false);
707 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
708 AUTH_ERROR_FIXED,
709 AUTH_ERROR_LIMIT);
712 if (HasSyncingBackend())
713 backend_->UpdateCredentials(GetCredentials());
714 else
715 startup_controller_->TryStart();
718 void ProfileSyncService::OnGetTokenFailure(
719 const OAuth2TokenService::Request* request,
720 const GoogleServiceAuthError& error) {
721 DCHECK_EQ(access_token_request_, request);
722 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
723 access_token_request_.reset();
724 last_get_token_error_ = error;
725 switch (error.state()) {
726 case GoogleServiceAuthError::CONNECTION_FAILED:
727 case GoogleServiceAuthError::REQUEST_CANCELED:
728 case GoogleServiceAuthError::SERVICE_ERROR:
729 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
730 // Transient error. Retry after some time.
731 request_access_token_backoff_.InformOfRequest(false);
732 next_token_request_time_ = base::Time::Now() +
733 request_access_token_backoff_.GetTimeUntilRelease();
734 request_access_token_retry_timer_.Start(
735 FROM_HERE,
736 request_access_token_backoff_.GetTimeUntilRelease(),
737 base::Bind(&ProfileSyncService::RequestAccessToken,
738 weak_factory_.GetWeakPtr()));
739 NotifyObservers();
740 break;
742 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
743 if (!sync_prefs_.SyncHasAuthError()) {
744 sync_prefs_.SetSyncAuthError(true);
745 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
746 AUTH_ERROR_ENCOUNTERED,
747 AUTH_ERROR_LIMIT);
749 // Fallthrough.
751 default: {
752 if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
753 LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
755 // Show error to user.
756 UpdateAuthErrorState(error);
761 void ProfileSyncService::OnRefreshTokenAvailable(
762 const std::string& account_id) {
763 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
764 // fixed.
765 tracked_objects::ScopedTracker tracking_profile(
766 FROM_HERE_WITH_EXPLICIT_FUNCTION(
767 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
769 if (account_id == signin_->GetAccountIdToUse())
770 OnRefreshTokensLoaded();
773 void ProfileSyncService::OnRefreshTokenRevoked(
774 const std::string& account_id) {
775 if (!IsOAuthRefreshTokenAvailable()) {
776 access_token_.clear();
777 // The additional check around IsOAuthRefreshTokenAvailable() above
778 // prevents us sounding the alarm if we actually have a valid token but
779 // a refresh attempt failed for any variety of reasons
780 // (e.g. flaky network). It's possible the token we do have is also
781 // invalid, but in that case we should already have (or can expect) an
782 // auth error sent from the sync backend.
783 UpdateAuthErrorState(
784 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
788 void ProfileSyncService::OnRefreshTokensLoaded() {
789 // This notification gets fired when OAuth2TokenService loads the tokens
790 // from storage.
791 // Initialize the backend if sync is enabled. If the sync token was
792 // not loaded, GetCredentials() will generate invalid credentials to
793 // cause the backend to generate an auth error (crbug.com/121755).
794 if (HasSyncingBackend()) {
795 RequestAccessToken();
796 } else {
797 startup_controller_->TryStart();
801 void ProfileSyncService::Shutdown() {
802 UnregisterAuthNotifications();
804 ShutdownImpl(syncer::BROWSER_SHUTDOWN);
805 if (sync_error_controller_) {
806 // Destroy the SyncErrorController when the service shuts down for good.
807 RemoveObserver(sync_error_controller_.get());
808 sync_error_controller_.reset();
811 if (sync_thread_)
812 sync_thread_->Stop();
815 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
816 if (!backend_) {
817 if (reason == syncer::ShutdownReason::DISABLE_SYNC && sync_thread_) {
818 // If the backend is already shut down when a DISABLE_SYNC happens,
819 // the data directory needs to be cleaned up here.
820 sync_thread_->task_runner()->PostTask(
821 FROM_HERE, base::Bind(&DeleteSyncDataFolder, directory_path_));
823 return;
826 if (reason == syncer::ShutdownReason::STOP_SYNC
827 || reason == syncer::ShutdownReason::DISABLE_SYNC) {
828 RemoveClientFromServer();
831 non_blocking_data_type_manager_.DisconnectSyncBackend();
833 // First, we spin down the backend to stop change processing as soon as
834 // possible.
835 base::Time shutdown_start_time = base::Time::Now();
836 backend_->StopSyncingForShutdown();
838 // Stop all data type controllers, if needed. Note that until Stop
839 // completes, it is possible in theory to have a ChangeProcessor apply a
840 // change from a native model. In that case, it will get applied to the sync
841 // database (which doesn't get destroyed until we destroy the backend below)
842 // as an unsynced change. That will be persisted, and committed on restart.
843 if (directory_data_type_manager_) {
844 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
845 // When aborting as part of shutdown, we should expect an aborted sync
846 // configure result, else we'll dcheck when we try to read the sync error.
847 expect_sync_configuration_aborted_ = true;
848 directory_data_type_manager_->Stop();
850 directory_data_type_manager_.reset();
853 // Shutdown the migrator before the backend to ensure it doesn't pull a null
854 // snapshot.
855 migrator_.reset();
856 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
858 // Move aside the backend so nobody else tries to use it while we are
859 // shutting it down.
860 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
861 if (doomed_backend) {
862 sync_thread_ = doomed_backend->Shutdown(reason);
863 doomed_backend.reset();
865 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
866 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
868 weak_factory_.InvalidateWeakPtrs();
870 if (backend_mode_ == SYNC)
871 startup_controller_->Reset(GetRegisteredDataTypes());
873 // Don't let backup block sync regardless backup succeeded or not.
874 if (backend_mode_ == BACKUP)
875 backup_finished_ = true;
877 // Sync could be blocked by rollback/backup. Post task to check whether sync
878 // should start after shutting down rollback/backup backend.
879 if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
880 reason != syncer::SWITCH_MODE_SYNC &&
881 reason != syncer::BROWSER_SHUTDOWN) {
882 base::ThreadTaskRunnerHandle::Get()->PostTask(
883 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
884 startup_controller_weak_factory_.GetWeakPtr()));
887 // Clear various flags.
888 backend_mode_ = IDLE;
889 expect_sync_configuration_aborted_ = false;
890 is_auth_in_progress_ = false;
891 backend_initialized_ = false;
892 cached_passphrase_.clear();
893 encryption_pending_ = false;
894 encrypt_everything_ = false;
895 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
896 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
897 request_access_token_retry_timer_.Stop();
898 // Revert to "no auth error".
899 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
900 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
902 NotifyObservers();
904 // Mark this as a clean shutdown(without crash).
905 sync_prefs_.SetCleanShutdown(true);
908 void ProfileSyncService::StopImpl(SyncStopDataFate data_fate) {
909 switch (data_fate) {
910 case KEEP_DATA:
911 // TODO(maxbogue): Investigate whether this logic can/should be moved
912 // into ShutdownImpl or SyncBackendHost itself.
913 if (HasSyncingBackend()) {
914 backend_->UnregisterInvalidationIds();
916 ShutdownImpl(syncer::STOP_SYNC);
917 break;
918 case CLEAR_DATA:
919 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
920 // PSS clients don't think we're set up while we're shutting down.
921 sync_prefs_.ClearPreferences();
922 ClearUnrecoverableError();
923 ShutdownImpl(syncer::DISABLE_SYNC);
924 break;
928 bool ProfileSyncService::HasSyncSetupCompleted() const {
929 return sync_prefs_.HasSyncSetupCompleted();
932 void ProfileSyncService::SetSyncSetupCompleted() {
933 sync_prefs_.SetSyncSetupCompleted();
936 void ProfileSyncService::UpdateLastSyncedTime() {
937 sync_prefs_.SetLastSyncedTime(base::Time::Now());
940 void ProfileSyncService::NotifyObservers() {
941 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
942 OnStateChanged());
945 void ProfileSyncService::NotifySyncCycleCompleted() {
946 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
947 OnSyncCycleCompleted());
950 void ProfileSyncService::ClearStaleErrors() {
951 ClearUnrecoverableError();
952 last_actionable_error_ = SyncProtocolError();
953 // Clear the data type errors as well.
954 if (directory_data_type_manager_.get())
955 directory_data_type_manager_->ResetDataTypeErrors();
959 void ProfileSyncService::ClearUnrecoverableError() {
960 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
961 unrecoverable_error_message_.clear();
962 unrecoverable_error_location_ = tracked_objects::Location();
965 // An invariant has been violated. Transition to an error state where we try
966 // to do as little work as possible, to avoid further corruption or crashes.
967 void ProfileSyncService::OnUnrecoverableError(
968 const tracked_objects::Location& from_here,
969 const std::string& message) {
970 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
971 // interface are assumed to originate within the syncer.
972 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
973 OnUnrecoverableErrorImpl(from_here, message, true);
976 void ProfileSyncService::OnUnrecoverableErrorImpl(
977 const tracked_objects::Location& from_here,
978 const std::string& message,
979 bool delete_sync_database) {
980 DCHECK(HasUnrecoverableError());
981 unrecoverable_error_message_ = message;
982 unrecoverable_error_location_ = from_here;
984 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
985 unrecoverable_error_reason_,
986 ERROR_REASON_LIMIT);
987 std::string location;
988 from_here.Write(true, true, &location);
989 LOG(ERROR)
990 << "Unrecoverable error detected at " << location
991 << " -- ProfileSyncService unusable: " << message;
993 // Shut all data types down.
994 base::ThreadTaskRunnerHandle::Get()->PostTask(
995 FROM_HERE,
996 base::Bind(
997 &ProfileSyncService::ShutdownImpl, weak_factory_.GetWeakPtr(),
998 delete_sync_database ? syncer::DISABLE_SYNC : syncer::STOP_SYNC));
1001 void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
1002 if (!backend_initialized_)
1003 return;
1004 directory_data_type_manager_->ReenableType(type);
1007 void ProfileSyncService::UpdateBackendInitUMA(bool success) {
1008 if (backend_mode_ != SYNC)
1009 return;
1011 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
1013 if (is_first_time_sync_configure_) {
1014 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
1015 } else {
1016 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
1019 base::Time on_backend_initialized_time = base::Time::Now();
1020 base::TimeDelta delta = on_backend_initialized_time -
1021 startup_controller_->start_backend_time();
1022 if (is_first_time_sync_configure_) {
1023 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1024 } else {
1025 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1029 void ProfileSyncService::PostBackendInitialization() {
1030 // Never get here for backup / restore.
1031 DCHECK_EQ(backend_mode_, SYNC);
1033 if (last_backup_time_) {
1034 DCHECK(device_info_sync_service_);
1035 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1038 if (protocol_event_observers_.might_have_observers()) {
1039 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1042 non_blocking_data_type_manager_.ConnectSyncBackend(
1043 backend_->GetSyncContextProxy());
1045 if (type_debug_info_observers_.might_have_observers()) {
1046 backend_->EnableDirectoryTypeDebugInfoForwarding();
1049 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1050 // backend is initialized. We want to call this before notifying observers in
1051 // case this operation affects the "passphrase required" status.
1052 ConsumeCachedPassphraseIfPossible();
1054 // The very first time the backend initializes is effectively the first time
1055 // we can say we successfully "synced". LastSyncedTime will only be null in
1056 // this case, because the pref wasn't restored on StartUp.
1057 if (sync_prefs_.GetLastSyncedTime().is_null()) {
1058 UpdateLastSyncedTime();
1061 if (startup_controller_->auto_start_enabled() && !FirstSetupInProgress()) {
1062 // Backend is initialized but we're not in sync setup, so this must be an
1063 // autostart - mark our sync setup as completed and we'll start syncing
1064 // below.
1065 SetSyncSetupCompleted();
1068 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1069 // data type configuration because observer may flag setup as complete and
1070 // trigger data type configuration.
1071 if (HasSyncSetupCompleted()) {
1072 ConfigureDataTypeManager();
1073 } else {
1074 DCHECK(FirstSetupInProgress());
1077 NotifyObservers();
1080 void ProfileSyncService::OnBackendInitialized(
1081 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1082 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1083 debug_info_listener,
1084 const std::string& cache_guid,
1085 bool success) {
1086 UpdateBackendInitUMA(success);
1088 if (!success) {
1089 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1090 // and surface error UI to alert the user sync has stopped.
1091 // Keep the directory around for now so that on restart we will retry
1092 // again and potentially succeed in presence of transient file IO failures
1093 // or permissions issues, etc.
1095 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1096 // Unlike every other UnrecoverableError, it does not delete our sync data.
1097 // This exception made sense at the time it was implemented, but our new
1098 // directory corruption recovery mechanism makes it obsolete. By the time
1099 // we get here, we will have already tried and failed to delete the
1100 // directory. It would be no big deal if we tried to delete it again.
1101 OnInternalUnrecoverableError(FROM_HERE,
1102 "BackendInitialize failure",
1103 false,
1104 ERROR_REASON_BACKEND_INIT_FAILURE);
1105 return;
1108 backend_initialized_ = true;
1110 sync_js_controller_.AttachJsBackend(js_backend);
1111 debug_info_listener_ = debug_info_listener;
1113 SigninClient* signin_client =
1114 ChromeSigninClientFactory::GetForProfile(profile_);
1115 DCHECK(signin_client);
1116 std::string signin_scoped_device_id =
1117 signin_client->GetSigninScopedDeviceId();
1119 // Initialize local device info.
1120 local_device_->Initialize(cache_guid, signin_scoped_device_id);
1122 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1123 non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1125 // Give the DataTypeControllers a handle to the now initialized backend
1126 // as a UserShare.
1127 for (DataTypeController::TypeMap::iterator it =
1128 directory_data_type_controllers_.begin();
1129 it != directory_data_type_controllers_.end(); ++it) {
1130 it->second->OnUserShareReady(GetUserShare());
1133 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1134 ConfigureDataTypeManager();
1135 else
1136 PostBackendInitialization();
1139 void ProfileSyncService::OnSyncCycleCompleted() {
1140 UpdateLastSyncedTime();
1141 if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1142 // Trigger garbage collection of old sessions now that we've downloaded
1143 // any new session data.
1144 base::ThreadTaskRunnerHandle::Get()->PostTask(
1145 FROM_HERE, base::Bind(&SessionsSyncManager::DoGarbageCollection,
1146 base::AsWeakPtr(sessions_sync_manager_.get())));
1148 DVLOG(2) << "Notifying observers sync cycle completed";
1149 NotifySyncCycleCompleted();
1152 void ProfileSyncService::OnExperimentsChanged(
1153 const syncer::Experiments& experiments) {
1154 if (current_experiments_.Matches(experiments))
1155 return;
1157 current_experiments_ = experiments;
1159 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1160 experiments.gcm_invalidations_enabled);
1161 profile()->GetPrefs()->SetBoolean(
1162 autofill::prefs::kAutofillWalletSyncExperimentEnabled,
1163 experiments.wallet_sync_enabled);
1166 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1167 is_auth_in_progress_ = false;
1168 last_auth_error_ = error;
1170 NotifyObservers();
1173 namespace {
1175 AuthError ConnectionStatusToAuthError(
1176 syncer::ConnectionStatus status) {
1177 switch (status) {
1178 case syncer::CONNECTION_OK:
1179 return AuthError::AuthErrorNone();
1180 break;
1181 case syncer::CONNECTION_AUTH_ERROR:
1182 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1183 break;
1184 case syncer::CONNECTION_SERVER_ERROR:
1185 return AuthError(AuthError::CONNECTION_FAILED);
1186 break;
1187 default:
1188 NOTREACHED();
1189 return AuthError(AuthError::CONNECTION_FAILED);
1193 } // namespace
1195 void ProfileSyncService::OnConnectionStatusChange(
1196 syncer::ConnectionStatus status) {
1197 connection_status_update_time_ = base::Time::Now();
1198 connection_status_ = status;
1199 if (status == syncer::CONNECTION_AUTH_ERROR) {
1200 // Sync server returned error indicating that access token is invalid. It
1201 // could be either expired or access is revoked. Let's request another
1202 // access token and if access is revoked then request for token will fail
1203 // with corresponding error. If access token is repeatedly reported
1204 // invalid, there may be some issues with server, e.g. authentication
1205 // state is inconsistent on sync and token server. In that case, we
1206 // backoff token requests exponentially to avoid hammering token server
1207 // too much and to avoid getting same token due to token server's caching
1208 // policy. |request_access_token_retry_timer_| is used to backoff request
1209 // triggered by both auth error and failure talking to GAIA server.
1210 // Therefore, we're likely to reach the backoff ceiling more quickly than
1211 // you would expect from looking at the BackoffPolicy if both types of
1212 // errors happen. We shouldn't receive two errors back-to-back without
1213 // attempting a token/sync request in between, thus crank up request delay
1214 // unnecessary. This is because we won't make a sync request if we hit an
1215 // error until GAIA succeeds at sending a new token, and we won't request
1216 // a new token unless sync reports a token failure. But to be safe, don't
1217 // schedule request if this happens.
1218 if (request_access_token_retry_timer_.IsRunning()) {
1219 // The timer to perform a request later is already running; nothing
1220 // further needs to be done at this point.
1221 } else if (request_access_token_backoff_.failure_count() == 0) {
1222 // First time request without delay. Currently invalid token is used
1223 // to initialize sync backend and we'll always end up here. We don't
1224 // want to delay initialization.
1225 request_access_token_backoff_.InformOfRequest(false);
1226 RequestAccessToken();
1227 } else {
1228 request_access_token_backoff_.InformOfRequest(false);
1229 request_access_token_retry_timer_.Start(
1230 FROM_HERE,
1231 request_access_token_backoff_.GetTimeUntilRelease(),
1232 base::Bind(&ProfileSyncService::RequestAccessToken,
1233 weak_factory_.GetWeakPtr()));
1235 } else {
1236 // Reset backoff time after successful connection.
1237 if (status == syncer::CONNECTION_OK) {
1238 // Request shouldn't be scheduled at this time. But if it is, it's
1239 // possible that sync flips between OK and auth error states rapidly,
1240 // thus hammers token server. To be safe, only reset backoff delay when
1241 // no scheduled request.
1242 if (request_access_token_retry_timer_.IsRunning()) {
1243 NOTREACHED();
1244 } else {
1245 request_access_token_backoff_.Reset();
1249 const GoogleServiceAuthError auth_error =
1250 ConnectionStatusToAuthError(status);
1251 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1252 UpdateAuthErrorState(auth_error);
1256 void ProfileSyncService::OnPassphraseRequired(
1257 syncer::PassphraseRequiredReason reason,
1258 const sync_pb::EncryptedData& pending_keys) {
1259 DCHECK(backend_.get());
1260 DCHECK(backend_->IsNigoriEnabled());
1262 // TODO(lipalani) : add this check to other locations as well.
1263 if (HasUnrecoverableError()) {
1264 // When unrecoverable error is detected we post a task to shutdown the
1265 // backend. The task might not have executed yet.
1266 return;
1269 DVLOG(1) << "Passphrase required with reason: "
1270 << syncer::PassphraseRequiredReasonToString(reason);
1271 passphrase_required_reason_ = reason;
1273 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1274 if (directory_data_type_manager_) {
1275 // Reconfigure without the encrypted types (excluded implicitly via the
1276 // failed datatypes handler).
1277 directory_data_type_manager_->Configure(types,
1278 syncer::CONFIGURE_REASON_CRYPTO);
1281 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1283 // Notify observers that the passphrase status may have changed.
1284 NotifyObservers();
1287 void ProfileSyncService::OnPassphraseAccepted() {
1288 DVLOG(1) << "Received OnPassphraseAccepted.";
1290 // If the pending keys were resolved via keystore, it's possible we never
1291 // consumed our cached passphrase. Clear it now.
1292 if (!cached_passphrase_.empty())
1293 cached_passphrase_.clear();
1295 // Reset passphrase_required_reason_ since we know we no longer require the
1296 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1297 // because that can be called by OnPassphraseRequired() if no encrypted data
1298 // types are enabled, and we don't want to clobber the true passphrase error.
1299 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1301 // Make sure the data types that depend on the passphrase are started at
1302 // this time.
1303 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1304 if (directory_data_type_manager_) {
1305 // Re-enable any encrypted types if necessary.
1306 directory_data_type_manager_->Configure(types,
1307 syncer::CONFIGURE_REASON_CRYPTO);
1310 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1312 NotifyObservers();
1315 void ProfileSyncService::OnEncryptedTypesChanged(
1316 syncer::ModelTypeSet encrypted_types,
1317 bool encrypt_everything) {
1318 encrypted_types_ = encrypted_types;
1319 encrypt_everything_ = encrypt_everything;
1320 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1321 DVLOG(1) << "Encrypted types changed to "
1322 << syncer::ModelTypeSetToString(encrypted_types_)
1323 << " (encrypt everything is set to "
1324 << (encrypt_everything_ ? "true" : "false") << ")";
1325 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1327 NotifyObservers();
1330 void ProfileSyncService::OnEncryptionComplete() {
1331 DVLOG(1) << "Encryption complete";
1332 if (encryption_pending_ && encrypt_everything_) {
1333 encryption_pending_ = false;
1334 // This is to nudge the integration tests when encryption is
1335 // finished.
1336 NotifyObservers();
1340 void ProfileSyncService::OnMigrationNeededForTypes(
1341 syncer::ModelTypeSet types) {
1342 DCHECK(backend_initialized_);
1343 DCHECK(directory_data_type_manager_.get());
1345 // Migrator must be valid, because we don't sync until it is created and this
1346 // callback originates from a sync cycle.
1347 migrator_->MigrateTypes(types);
1350 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1351 last_actionable_error_ = error;
1352 DCHECK_NE(last_actionable_error_.action,
1353 syncer::UNKNOWN_ACTION);
1354 switch (error.action) {
1355 case syncer::UPGRADE_CLIENT:
1356 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1357 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1358 case syncer::STOP_AND_RESTART_SYNC:
1359 // TODO(lipalani) : if setup in progress we want to display these
1360 // actions in the popup. The current experience might not be optimal for
1361 // the user. We just dismiss the dialog.
1362 if (startup_controller_->setup_in_progress()) {
1363 RequestStop(CLEAR_DATA);
1364 expect_sync_configuration_aborted_ = true;
1366 // Trigger an unrecoverable error to stop syncing.
1367 OnInternalUnrecoverableError(FROM_HERE,
1368 last_actionable_error_.error_description,
1369 true,
1370 ERROR_REASON_ACTIONABLE_ERROR);
1371 break;
1372 case syncer::DISABLE_SYNC_AND_ROLLBACK:
1373 backup_rollback_controller_->OnRollbackReceived();
1374 // Fall through to shutdown backend and sign user out.
1375 case syncer::DISABLE_SYNC_ON_CLIENT:
1376 RequestStop(CLEAR_DATA);
1377 #if !defined(OS_CHROMEOS)
1378 // On desktop Chrome, sign out the user after a dashboard clear.
1379 // Skip sign out on ChromeOS/Android.
1380 if (!startup_controller_->auto_start_enabled()) {
1381 SigninManagerFactory::GetForProfile(profile_)->SignOut(
1382 signin_metrics::SERVER_FORCED_DISABLE);
1384 #endif
1385 break;
1386 case syncer::ROLLBACK_DONE:
1387 backup_rollback_controller_->OnRollbackDone();
1388 break;
1389 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1390 // Sync disabled by domain admin. we should stop syncing until next
1391 // restart.
1392 sync_disabled_by_admin_ = true;
1393 ShutdownImpl(syncer::DISABLE_SYNC);
1394 break;
1395 default:
1396 NOTREACHED();
1398 NotifyObservers();
1400 if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1401 (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1402 !backup_rollback_controller_->StartRollback())) {
1403 // Clean up backup data for sign-out only or when rollback is disabled.
1404 CleanUpBackup();
1405 } else if (error.action == syncer::ROLLBACK_DONE) {
1406 // Shut down ROLLBACK backend and delete backup DB.
1407 ShutdownImpl(syncer::DISABLE_SYNC);
1408 sync_prefs_.ClearFirstSyncTime();
1412 void ProfileSyncService::OnLocalSetPassphraseEncryption(
1413 const syncer::SyncEncryptionHandler::NigoriState& nigori_state) {
1414 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
1415 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1416 switches::kSyncEnableClearDataOnPassphraseEncryption))
1417 return;
1419 // At this point the user has set a custom passphrase and we
1420 // have received the updated nigori state. Time to cache the nigori state,
1421 // shutdown sync, then restart it and restore the cached nigori state.
1422 ShutdownImpl(syncer::DISABLE_SYNC);
1423 saved_nigori_state_.reset(
1424 new syncer::SyncEncryptionHandler::NigoriState(nigori_state));
1425 // TODO(maniscalco): We should also clear the bootstrap keystore key from the
1426 // pref before restarting sync to ensure we obtain a new, valid one when we
1427 // perform the configuration sync cycle (crbug.com/490836).
1428 startup_controller_->TryStart();
1431 void ProfileSyncService::OnConfigureDone(
1432 const DataTypeManager::ConfigureResult& result) {
1433 configure_status_ = result.status;
1434 data_type_status_table_ = result.data_type_status_table;
1436 if (backend_mode_ != SYNC) {
1437 if (configure_status_ == DataTypeManager::OK) {
1438 StartSyncingWithServer();
1440 // Backup is done after models are associated.
1441 if (backend_mode_ == BACKUP)
1442 backup_finished_ = true;
1444 // Asynchronously check whether sync needs to start.
1445 base::ThreadTaskRunnerHandle::Get()->PostTask(
1446 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1447 startup_controller_weak_factory_.GetWeakPtr()));
1448 } else if (!expect_sync_configuration_aborted_) {
1449 DVLOG(1) << "Backup/rollback backend failed to configure.";
1450 ShutdownImpl(syncer::STOP_SYNC);
1453 return;
1456 // We should have cleared our cached passphrase before we get here (in
1457 // OnBackendInitialized()).
1458 DCHECK(cached_passphrase_.empty());
1460 if (!sync_configure_start_time_.is_null()) {
1461 if (result.status == DataTypeManager::OK) {
1462 base::Time sync_configure_stop_time = base::Time::Now();
1463 base::TimeDelta delta = sync_configure_stop_time -
1464 sync_configure_start_time_;
1465 if (is_first_time_sync_configure_) {
1466 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1467 } else {
1468 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1469 delta);
1472 sync_configure_start_time_ = base::Time();
1475 // Notify listeners that configuration is done.
1476 content::NotificationService::current()->Notify(
1477 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1478 content::Source<ProfileSyncService>(this),
1479 content::NotificationService::NoDetails());
1481 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1482 // The possible status values:
1483 // ABORT - Configuration was aborted. This is not an error, if
1484 // initiated by user.
1485 // OK - Some or all types succeeded.
1486 // Everything else is an UnrecoverableError. So treat it as such.
1488 // First handle the abort case.
1489 if (configure_status_ == DataTypeManager::ABORTED &&
1490 expect_sync_configuration_aborted_) {
1491 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1492 expect_sync_configuration_aborted_ = false;
1493 return;
1496 // Handle unrecoverable error.
1497 if (configure_status_ != DataTypeManager::OK) {
1498 // Something catastrophic had happened. We should only have one
1499 // error representing it.
1500 syncer::SyncError error =
1501 data_type_status_table_.GetUnrecoverableError();
1502 DCHECK(error.IsSet());
1503 std::string message =
1504 "Sync configuration failed with status " +
1505 DataTypeManager::ConfigureStatusToString(configure_status_) +
1506 " caused by " +
1507 syncer::ModelTypeSetToString(
1508 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1509 ": " + error.message();
1510 LOG(ERROR) << "ProfileSyncService error: " << message;
1511 OnInternalUnrecoverableError(error.location(),
1512 message,
1513 true,
1514 ERROR_REASON_CONFIGURATION_FAILURE);
1515 return;
1518 // We should never get in a state where we have no encrypted datatypes
1519 // enabled, and yet we still think we require a passphrase for decryption.
1520 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1521 !IsEncryptedDatatypeEnabled()));
1523 // This must be done before we start syncing with the server to avoid
1524 // sending unencrypted data up on a first time sync.
1525 if (encryption_pending_)
1526 backend_->EnableEncryptEverything();
1527 NotifyObservers();
1529 if (migrator_.get() &&
1530 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1531 // Migration in progress. Let the migrator know we just finished
1532 // configuring something. It will be up to the migrator to call
1533 // StartSyncingWithServer() if migration is now finished.
1534 migrator_->OnConfigureDone(result);
1535 } else {
1536 StartSyncingWithServer();
1540 void ProfileSyncService::OnConfigureStart() {
1541 sync_configure_start_time_ = base::Time::Now();
1542 NotifyObservers();
1545 ProfileSyncService::SyncStatusSummary
1546 ProfileSyncService::QuerySyncStatusSummary() {
1547 if (HasUnrecoverableError()) {
1548 return UNRECOVERABLE_ERROR;
1549 } else if (!backend_) {
1550 return NOT_ENABLED;
1551 } else if (backend_mode_ == BACKUP) {
1552 return BACKUP_USER_DATA;
1553 } else if (backend_mode_ == ROLLBACK) {
1554 return ROLLBACK_USER_DATA;
1555 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1556 return SETUP_INCOMPLETE;
1557 } else if (
1558 backend_.get() && HasSyncSetupCompleted() &&
1559 directory_data_type_manager_.get() &&
1560 directory_data_type_manager_->state() == DataTypeManager::STOPPED) {
1561 return DATATYPES_NOT_INITIALIZED;
1562 } else if (IsSyncActive()) {
1563 return INITIALIZED;
1565 return UNKNOWN_ERROR;
1568 std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1569 SyncStatusSummary status = QuerySyncStatusSummary();
1571 std::string config_status_str =
1572 configure_status_ != DataTypeManager::UNKNOWN ?
1573 DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1575 switch (status) {
1576 case UNRECOVERABLE_ERROR:
1577 return "Unrecoverable error detected";
1578 case NOT_ENABLED:
1579 return "Syncing not enabled";
1580 case SETUP_INCOMPLETE:
1581 return "First time sync setup incomplete";
1582 case DATATYPES_NOT_INITIALIZED:
1583 return "Datatypes not fully initialized";
1584 case INITIALIZED:
1585 return "Sync service initialized";
1586 case BACKUP_USER_DATA:
1587 return "Backing-up user data. Status: " + config_status_str;
1588 case ROLLBACK_USER_DATA:
1589 return "Restoring user data. Status: " + config_status_str;
1590 default:
1591 return "Status unknown: Internal error?";
1595 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1596 return startup_controller_->GetBackendInitializationStateString();
1599 bool ProfileSyncService::auto_start_enabled() const {
1600 return startup_controller_->auto_start_enabled();
1603 bool ProfileSyncService::setup_in_progress() const {
1604 return startup_controller_->setup_in_progress();
1607 bool ProfileSyncService::QueryDetailedSyncStatus(
1608 SyncBackendHost::Status* result) {
1609 if (backend_.get() && backend_initialized_) {
1610 *result = backend_->GetDetailedStatus();
1611 return true;
1612 } else {
1613 SyncBackendHost::Status status;
1614 status.sync_protocol_error = last_actionable_error_;
1615 *result = status;
1616 return false;
1620 const AuthError& ProfileSyncService::GetAuthError() const {
1621 return last_auth_error_;
1624 bool ProfileSyncService::FirstSetupInProgress() const {
1625 return !HasSyncSetupCompleted() && startup_controller_->setup_in_progress();
1628 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1629 // This method is a no-op if |setup_in_progress_| remains unchanged.
1630 if (startup_controller_->setup_in_progress() == setup_in_progress)
1631 return;
1633 startup_controller_->set_setup_in_progress(setup_in_progress);
1634 if (!setup_in_progress && backend_initialized())
1635 ReconfigureDatatypeManager();
1636 NotifyObservers();
1639 bool ProfileSyncService::IsSyncAllowed() const {
1640 return IsSyncAllowedByFlag() && !IsManaged();
1643 bool ProfileSyncService::IsSyncActive() const {
1644 return backend_initialized_ && backend_mode_ == SYNC &&
1645 directory_data_type_manager_ &&
1646 directory_data_type_manager_->state() != DataTypeManager::STOPPED;
1649 bool ProfileSyncService::IsSignedIn() const {
1650 // Sync is logged in if there is a non-empty effective account id.
1651 return !signin_->GetAccountIdToUse().empty();
1654 bool ProfileSyncService::backend_initialized() const {
1655 return backend_initialized_;
1658 ProfileSyncService::BackendMode ProfileSyncService::backend_mode() const {
1659 return backend_mode_;
1662 bool ProfileSyncService::ConfigurationDone() const {
1663 return directory_data_type_manager_ &&
1664 directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
1667 bool ProfileSyncService::waiting_for_auth() const {
1668 return is_auth_in_progress_;
1671 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1672 return current_experiments_;
1675 bool ProfileSyncService::HasUnrecoverableError() const {
1676 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1679 bool ProfileSyncService::IsPassphraseRequired() const {
1680 return passphrase_required_reason_ !=
1681 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1684 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1685 // If there is an encrypted datatype enabled and we don't have the proper
1686 // passphrase, we must prompt the user for a passphrase. The only way for the
1687 // user to avoid entering their passphrase is to disable the encrypted types.
1688 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1691 base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1692 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
1693 if (last_synced_time.is_null())
1694 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1696 base::TimeDelta time_since_last_sync = base::Time::Now() - last_synced_time;
1698 if (time_since_last_sync < base::TimeDelta::FromMinutes(1))
1699 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1701 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1702 ui::TimeFormat::LENGTH_SHORT,
1703 time_since_last_sync);
1706 void ProfileSyncService::UpdateSelectedTypesHistogram(
1707 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1708 if (!HasSyncSetupCompleted() ||
1709 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1710 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1713 // Only log the data types that are shown in the sync settings ui.
1714 // Note: the order of these types must match the ordering of
1715 // the respective types in ModelType
1716 const sync_driver::user_selectable_type::UserSelectableSyncType
1717 user_selectable_types[] = {
1718 sync_driver::user_selectable_type::BOOKMARKS,
1719 sync_driver::user_selectable_type::PREFERENCES,
1720 sync_driver::user_selectable_type::PASSWORDS,
1721 sync_driver::user_selectable_type::AUTOFILL,
1722 sync_driver::user_selectable_type::THEMES,
1723 sync_driver::user_selectable_type::TYPED_URLS,
1724 sync_driver::user_selectable_type::EXTENSIONS,
1725 sync_driver::user_selectable_type::APPS,
1726 sync_driver::user_selectable_type::WIFI_CREDENTIAL,
1727 sync_driver::user_selectable_type::PROXY_TABS,
1730 static_assert(36 == syncer::MODEL_TYPE_COUNT,
1731 "custom config histogram must be updated");
1733 if (!sync_everything) {
1734 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1736 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1737 syncer::ModelTypeSet::Iterator it = type_set.First();
1739 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1741 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1742 ++i, it.Inc()) {
1743 const syncer::ModelType type = it.Get();
1744 if (chosen_types.Has(type) &&
1745 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1746 // Selected type has changed - log it.
1747 UMA_HISTOGRAM_ENUMERATION(
1748 "Sync.CustomSync",
1749 user_selectable_types[i],
1750 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1756 #if defined(OS_CHROMEOS)
1757 void ProfileSyncService::RefreshSpareBootstrapToken(
1758 const std::string& passphrase) {
1759 sync_driver::SystemEncryptor encryptor;
1760 syncer::Cryptographer temp_cryptographer(&encryptor);
1761 // The first 2 params (hostname and username) doesn't have any effect here.
1762 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1764 std::string bootstrap_token;
1765 if (!temp_cryptographer.AddKey(key_params)) {
1766 NOTREACHED() << "Failed to add key to cryptographer.";
1768 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1769 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1771 #endif
1773 void ProfileSyncService::OnUserChoseDatatypes(
1774 bool sync_everything,
1775 syncer::ModelTypeSet chosen_types) {
1776 if (!backend_.get() && !HasUnrecoverableError()) {
1777 NOTREACHED();
1778 return;
1781 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1782 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1784 if (directory_data_type_manager_.get())
1785 directory_data_type_manager_->ResetDataTypeErrors();
1786 ChangePreferredDataTypes(chosen_types);
1789 void ProfileSyncService::ChangePreferredDataTypes(
1790 syncer::ModelTypeSet preferred_types) {
1792 DVLOG(1) << "ChangePreferredDataTypes invoked";
1793 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1794 // Will only enable those types that are registered and preferred.
1795 sync_prefs_.SetPreferredDataTypes(registered_types, preferred_types);
1797 // Now reconfigure the DTM.
1798 ReconfigureDatatypeManager();
1800 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1801 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1802 // which types should be enabled and when.
1805 syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1806 if (!IsSyncActive() || !ConfigurationDone())
1807 return syncer::ModelTypeSet();
1808 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1809 const syncer::ModelTypeSet failed_types =
1810 data_type_status_table_.GetFailedTypes();
1811 return Difference(preferred_types, failed_types);
1814 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1815 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1816 const syncer::ModelTypeSet preferred_types =
1817 sync_prefs_.GetPreferredDataTypes(registered_types);
1818 const syncer::ModelTypeSet enforced_types =
1819 Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1820 return Union(preferred_types, enforced_types);
1823 syncer::ModelTypeSet
1824 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1825 const syncer::ModelTypeSet registered_directory_types =
1826 GetRegisteredDirectoryDataTypes();
1827 const syncer::ModelTypeSet preferred_types =
1828 sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1829 const syncer::ModelTypeSet enforced_types =
1830 Intersection(GetDataTypesFromPreferenceProviders(),
1831 registered_directory_types);
1832 return Union(preferred_types, enforced_types);
1835 syncer::ModelTypeSet
1836 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1837 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1840 syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1841 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1842 // we'll need another way to distinguish user-choosable types from
1843 // programmatically-enabled types.
1844 return GetDataTypesFromPreferenceProviders();
1847 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1848 return Union(GetRegisteredDirectoryDataTypes(),
1849 GetRegisteredNonBlockingDataTypes());
1852 syncer::ModelTypeSet
1853 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1854 syncer::ModelTypeSet registered_types;
1855 // The directory_data_type_controllers_ are determined by command-line flags;
1856 // that's effectively what controls the values returned here.
1857 for (DataTypeController::TypeMap::const_iterator it =
1858 directory_data_type_controllers_.begin();
1859 it != directory_data_type_controllers_.end(); ++it) {
1860 registered_types.Put(it->first);
1862 return registered_types;
1865 syncer::ModelTypeSet
1866 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1867 return non_blocking_data_type_manager_.GetRegisteredTypes();
1870 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1871 syncer::PassphraseType passphrase_type = GetPassphraseType();
1872 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1873 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1876 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1877 return backend_->GetPassphraseType();
1880 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1881 return backend_->GetExplicitPassphraseTime();
1884 bool ProfileSyncService::IsCryptographerReady(
1885 const syncer::BaseTransaction* trans) const {
1886 return backend_.get() && backend_->IsCryptographerReady(trans);
1889 void ProfileSyncService::ConfigureDataTypeManager() {
1890 // Don't configure datatypes if the setup UI is still on the screen - this
1891 // is to help multi-screen setting UIs (like iOS) where they don't want to
1892 // start syncing data until the user is done configuring encryption options,
1893 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1894 // SetSetupInProgress(false).
1895 if (backend_mode_ == SYNC && startup_controller_->setup_in_progress())
1896 return;
1898 bool restart = false;
1899 if (!directory_data_type_manager_) {
1900 restart = true;
1901 directory_data_type_manager_.reset(
1902 factory_->CreateDataTypeManager(debug_info_listener_,
1903 &directory_data_type_controllers_,
1904 this,
1905 backend_.get(),
1906 this));
1908 // We create the migrator at the same time.
1909 migrator_.reset(
1910 new browser_sync::BackendMigrator(
1911 profile_->GetDebugName(), GetUserShare(),
1912 this, directory_data_type_manager_.get(),
1913 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1914 base::Unretained(this))));
1917 syncer::ModelTypeSet types;
1918 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1919 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1920 types = syncer::BackupTypes();
1921 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1922 } else {
1923 types = GetPreferredDirectoryDataTypes();
1924 if (!HasSyncSetupCompleted()) {
1925 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1926 } else if (restart) {
1927 // Datatype downloads on restart are generally due to newly supported
1928 // datatypes (although it's also possible we're picking up where a failed
1929 // previous configuration left off).
1930 // TODO(sync): consider detecting configuration recovery and setting
1931 // the reason here appropriately.
1932 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1933 } else {
1934 // The user initiated a reconfiguration (either to add or remove types).
1935 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1939 directory_data_type_manager_->Configure(types, reason);
1942 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1943 if (backend_.get() && backend_initialized_) {
1944 return backend_->GetUserShare();
1946 NOTREACHED();
1947 return NULL;
1950 syncer::sessions::SyncSessionSnapshot
1951 ProfileSyncService::GetLastSessionSnapshot() const {
1952 if (backend_)
1953 return backend_->GetLastSessionSnapshot();
1954 return syncer::sessions::SyncSessionSnapshot();
1957 bool ProfileSyncService::HasUnsyncedItems() const {
1958 if (HasSyncingBackend() && backend_initialized_) {
1959 return backend_->HasUnsyncedItems();
1961 NOTREACHED();
1962 return false;
1965 browser_sync::BackendMigrator*
1966 ProfileSyncService::GetBackendMigratorForTest() {
1967 return migrator_.get();
1970 void ProfileSyncService::GetModelSafeRoutingInfo(
1971 syncer::ModelSafeRoutingInfo* out) const {
1972 if (backend_.get() && backend_initialized_) {
1973 backend_->GetModelSafeRoutingInfo(out);
1974 } else {
1975 NOTREACHED();
1979 base::Value* ProfileSyncService::GetTypeStatusMap() const {
1980 scoped_ptr<base::ListValue> result(new base::ListValue());
1982 if (!backend_.get() || !backend_initialized_) {
1983 return result.release();
1986 DataTypeStatusTable::TypeErrorMap error_map =
1987 data_type_status_table_.GetAllErrors();
1988 ModelTypeSet active_types;
1989 ModelTypeSet passive_types;
1990 ModelSafeRoutingInfo routing_info;
1991 backend_->GetModelSafeRoutingInfo(&routing_info);
1992 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1993 it != routing_info.end(); ++it) {
1994 if (it->second == syncer::GROUP_PASSIVE) {
1995 passive_types.Put(it->first);
1996 } else {
1997 active_types.Put(it->first);
2001 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
2002 ModelTypeSet &throttled_types(detailed_status.throttled_types);
2003 ModelTypeSet registered = GetRegisteredDataTypes();
2004 scoped_ptr<base::DictionaryValue> type_status_header(
2005 new base::DictionaryValue());
2007 type_status_header->SetString("name", "Model Type");
2008 type_status_header->SetString("status", "header");
2009 type_status_header->SetString("value", "Group Type");
2010 type_status_header->SetString("num_entries", "Total Entries");
2011 type_status_header->SetString("num_live", "Live Entries");
2012 result->Append(type_status_header.release());
2014 scoped_ptr<base::DictionaryValue> type_status;
2015 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2016 ModelType type = it.Get();
2018 type_status.reset(new base::DictionaryValue());
2019 type_status->SetString("name", ModelTypeToString(type));
2021 if (error_map.find(type) != error_map.end()) {
2022 const syncer::SyncError &error = error_map.find(type)->second;
2023 DCHECK(error.IsSet());
2024 switch (error.GetSeverity()) {
2025 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2026 std::string error_text = "Error: " + error.location().ToString() +
2027 ", " + error.GetMessagePrefix() + error.message();
2028 type_status->SetString("status", "error");
2029 type_status->SetString("value", error_text);
2031 break;
2032 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2033 type_status->SetString("status", "disabled");
2034 type_status->SetString("value", error.message());
2035 break;
2036 default:
2037 NOTREACHED() << "Unexpected error severity.";
2038 break;
2040 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2041 // Show a proxy type in "ok" state unless it is disabled by user.
2042 DCHECK(!throttled_types.Has(type));
2043 type_status->SetString("status", "ok");
2044 type_status->SetString("value", "Passive");
2045 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2046 type_status->SetString("status", "warning");
2047 type_status->SetString("value", "Passive, Throttled");
2048 } else if (passive_types.Has(type)) {
2049 type_status->SetString("status", "warning");
2050 type_status->SetString("value", "Passive");
2051 } else if (throttled_types.Has(type)) {
2052 type_status->SetString("status", "warning");
2053 type_status->SetString("value", "Throttled");
2054 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2055 type_status->SetString("status", "ok");
2056 type_status->SetString("value", "Non-Blocking");
2057 } else if (active_types.Has(type)) {
2058 type_status->SetString("status", "ok");
2059 type_status->SetString("value", "Active: " +
2060 ModelSafeGroupToString(routing_info[type]));
2061 } else {
2062 type_status->SetString("status", "warning");
2063 type_status->SetString("value", "Disabled by User");
2066 int live_count = detailed_status.num_entries_by_type[type] -
2067 detailed_status.num_to_delete_entries_by_type[type];
2068 type_status->SetInteger("num_entries",
2069 detailed_status.num_entries_by_type[type]);
2070 type_status->SetInteger("num_live", live_count);
2072 result->Append(type_status.release());
2074 return result.release();
2077 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2078 if (!backend_)
2079 return;
2080 backend_->DeactivateDataType(type);
2083 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2084 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2085 // If the backend isn't running yet, OnBackendInitialized() will call this
2086 // method again after the backend starts up.
2087 if (cached_passphrase_.empty() || !backend_initialized())
2088 return;
2090 // Backend is up and running, so we can consume the cached passphrase.
2091 std::string passphrase = cached_passphrase_;
2092 cached_passphrase_.clear();
2094 // If we need a passphrase to decrypt data, try the cached passphrase.
2095 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2096 if (SetDecryptionPassphrase(passphrase)) {
2097 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2098 return;
2102 // If we get here, we don't have pending keys (or at least, the passphrase
2103 // doesn't decrypt them) - just try to re-encrypt using the encryption
2104 // passphrase.
2105 if (!IsUsingSecondaryPassphrase())
2106 SetEncryptionPassphrase(passphrase, IMPLICIT);
2109 void ProfileSyncService::RequestAccessToken() {
2110 // Only one active request at a time.
2111 if (access_token_request_ != NULL)
2112 return;
2113 request_access_token_retry_timer_.Stop();
2114 OAuth2TokenService::ScopeSet oauth2_scopes;
2115 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2117 // Invalidate previous token, otherwise token service will return the same
2118 // token again.
2119 const std::string& account_id = signin_->GetAccountIdToUse();
2120 if (!access_token_.empty()) {
2121 oauth2_token_service_->InvalidateAccessToken(account_id, oauth2_scopes,
2122 access_token_);
2125 access_token_.clear();
2127 token_request_time_ = base::Time::Now();
2128 token_receive_time_ = base::Time();
2129 next_token_request_time_ = base::Time();
2130 access_token_request_ =
2131 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2134 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2135 PassphraseType type) {
2136 // This should only be called when the backend has been initialized.
2137 DCHECK(backend_initialized());
2138 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2139 "Data is already encrypted using an explicit passphrase";
2140 DCHECK(!(type == EXPLICIT &&
2141 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2142 "Can not set explicit passphrase when decryption is needed.";
2144 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2145 << " passphrase for encryption.";
2146 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2147 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2148 // keys. Hence, as long as we're not trying to do an invalid passphrase
2149 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2150 // will succeed. If for some reason a new encryption key arrives via
2151 // sync later, the SBH will trigger another OnPassphraseRequired().
2152 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2153 NotifyObservers();
2155 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2158 bool ProfileSyncService::SetDecryptionPassphrase(
2159 const std::string& passphrase) {
2160 if (IsPassphraseRequired()) {
2161 DVLOG(1) << "Setting passphrase for decryption.";
2162 bool result = backend_->SetDecryptionPassphrase(passphrase);
2163 UMA_HISTOGRAM_BOOLEAN("Sync.PassphraseDecryptionSucceeded", result);
2164 return result;
2165 } else {
2166 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2167 "IsPassphraseRequired() is false.";
2168 return false;
2172 bool ProfileSyncService::EncryptEverythingAllowed() const {
2173 return encrypt_everything_allowed_;
2176 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2177 DCHECK(allowed || !backend_initialized() || !EncryptEverythingEnabled());
2178 encrypt_everything_allowed_ = allowed;
2181 void ProfileSyncService::EnableEncryptEverything() {
2182 DCHECK(EncryptEverythingAllowed());
2184 // Tests override backend_initialized() to always return true, so we
2185 // must check that instead of |backend_initialized_|.
2186 // TODO(akalin): Fix the above. :/
2187 DCHECK(backend_initialized());
2188 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2189 // problems around cancelling encryption in the background (crbug.com/119649).
2190 if (!encrypt_everything_)
2191 encryption_pending_ = true;
2194 bool ProfileSyncService::encryption_pending() const {
2195 // We may be called during the setup process before we're
2196 // initialized (via IsEncryptedDatatypeEnabled and
2197 // IsPassphraseRequiredForDecryption).
2198 return encryption_pending_;
2201 bool ProfileSyncService::EncryptEverythingEnabled() const {
2202 DCHECK(backend_initialized_);
2203 return encrypt_everything_ || encryption_pending_;
2206 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2207 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2208 // We may be called during the setup process before we're
2209 // initialized. In this case, we default to the sensitive types.
2210 return encrypted_types_;
2213 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2214 if (is_sync_managed) {
2215 StopImpl(CLEAR_DATA);
2216 } else {
2217 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2218 startup_controller_->TryStart();
2222 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2223 const std::string& username,
2224 const std::string& password) {
2225 if (IsSyncRequested() && !password.empty()) {
2226 cached_passphrase_ = password;
2227 // Try to consume the passphrase we just cached. If the sync backend
2228 // is not running yet, the passphrase will remain cached until the
2229 // backend starts up.
2230 ConsumeCachedPassphraseIfPossible();
2232 #if defined(OS_CHROMEOS)
2233 RefreshSpareBootstrapToken(password);
2234 #endif
2235 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE) {
2236 // Track the fact that we're still waiting for auth to complete.
2237 is_auth_in_progress_ = true;
2241 void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2242 const std::string& username) {
2243 sync_disabled_by_admin_ = false;
2244 RequestStop(CLEAR_DATA);
2246 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2247 need_backup_ = true;
2248 backup_finished_ = false;
2252 void ProfileSyncService::AddObserver(
2253 sync_driver::SyncServiceObserver* observer) {
2254 observers_.AddObserver(observer);
2257 void ProfileSyncService::RemoveObserver(
2258 sync_driver::SyncServiceObserver* observer) {
2259 observers_.RemoveObserver(observer);
2262 void ProfileSyncService::AddProtocolEventObserver(
2263 browser_sync::ProtocolEventObserver* observer) {
2264 protocol_event_observers_.AddObserver(observer);
2265 if (HasSyncingBackend()) {
2266 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2270 void ProfileSyncService::RemoveProtocolEventObserver(
2271 browser_sync::ProtocolEventObserver* observer) {
2272 protocol_event_observers_.RemoveObserver(observer);
2273 if (HasSyncingBackend() &&
2274 !protocol_event_observers_.might_have_observers()) {
2275 backend_->DisableProtocolEventForwarding();
2279 void ProfileSyncService::AddTypeDebugInfoObserver(
2280 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2281 type_debug_info_observers_.AddObserver(type_debug_info_observer);
2282 if (type_debug_info_observers_.might_have_observers() &&
2283 backend_initialized_) {
2284 backend_->EnableDirectoryTypeDebugInfoForwarding();
2288 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2289 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2290 type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2291 if (!type_debug_info_observers_.might_have_observers() &&
2292 backend_initialized_) {
2293 backend_->DisableDirectoryTypeDebugInfoForwarding();
2297 void ProfileSyncService::AddPreferenceProvider(
2298 SyncTypePreferenceProvider* provider) {
2299 DCHECK(!HasPreferenceProvider(provider))
2300 << "Providers may only be added once!";
2301 preference_providers_.insert(provider);
2304 void ProfileSyncService::RemovePreferenceProvider(
2305 SyncTypePreferenceProvider* provider) {
2306 DCHECK(HasPreferenceProvider(provider))
2307 << "Only providers that have been added before can be removed!";
2308 preference_providers_.erase(provider);
2311 bool ProfileSyncService::HasPreferenceProvider(
2312 SyncTypePreferenceProvider* provider) const {
2313 return preference_providers_.count(provider) > 0;
2316 namespace {
2318 class GetAllNodesRequestHelper
2319 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2320 public:
2321 GetAllNodesRequestHelper(
2322 syncer::ModelTypeSet requested_types,
2323 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2325 void OnReceivedNodesForTypes(
2326 const std::vector<syncer::ModelType>& types,
2327 ScopedVector<base::ListValue> scoped_node_lists);
2329 private:
2330 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2331 virtual ~GetAllNodesRequestHelper();
2333 scoped_ptr<base::ListValue> result_accumulator_;
2335 syncer::ModelTypeSet awaiting_types_;
2336 base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2339 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2340 syncer::ModelTypeSet requested_types,
2341 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2342 : result_accumulator_(new base::ListValue()),
2343 awaiting_types_(requested_types),
2344 callback_(callback) {}
2346 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2347 if (!awaiting_types_.Empty()) {
2348 DLOG(WARNING)
2349 << "GetAllNodesRequest deleted before request was fulfilled. "
2350 << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2354 // Called when the set of nodes for a type or set of types has been returned.
2356 // The nodes for several types can be returned at the same time by specifying
2357 // their types in the |types| array, and putting their results at the
2358 // correspnding indices in the |scoped_node_lists|.
2359 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2360 const std::vector<syncer::ModelType>& types,
2361 ScopedVector<base::ListValue> scoped_node_lists) {
2362 DCHECK_EQ(types.size(), scoped_node_lists.size());
2364 // Take unsafe ownership of the node list.
2365 std::vector<base::ListValue*> node_lists;
2366 scoped_node_lists.release(&node_lists);
2368 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2369 const ModelType type = types[i];
2370 base::ListValue* node_list = node_lists[i];
2372 // Add these results to our list.
2373 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2374 type_dict->SetString("type", ModelTypeToString(type));
2375 type_dict->Set("nodes", node_list);
2376 result_accumulator_->Append(type_dict.release());
2378 // Remember that this part of the request is satisfied.
2379 awaiting_types_.Remove(type);
2382 if (awaiting_types_.Empty()) {
2383 callback_.Run(result_accumulator_.Pass());
2384 callback_.Reset();
2388 } // namespace
2390 void ProfileSyncService::GetAllNodes(
2391 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2392 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2393 directory_types.PutAll(syncer::ControlTypes());
2394 scoped_refptr<GetAllNodesRequestHelper> helper =
2395 new GetAllNodesRequestHelper(directory_types, callback);
2397 if (!backend_initialized_) {
2398 // If there's no backend available to fulfill the request, handle it here.
2399 ScopedVector<base::ListValue> empty_results;
2400 std::vector<ModelType> type_vector;
2401 for (ModelTypeSet::Iterator it = directory_types.First();
2402 it.Good(); it.Inc()) {
2403 type_vector.push_back(it.Get());
2404 empty_results.push_back(new base::ListValue());
2406 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2407 } else {
2408 backend_->GetAllNodesForTypes(
2409 directory_types,
2410 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2414 bool ProfileSyncService::HasObserver(
2415 const sync_driver::SyncServiceObserver* observer) const {
2416 return observers_.HasObserver(observer);
2419 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2420 return sync_js_controller_.AsWeakPtr();
2423 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2424 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2427 // static
2428 bool ProfileSyncService::IsSyncAllowedByFlag() {
2429 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2430 switches::kDisableSync);
2433 bool ProfileSyncService::IsManaged() const {
2434 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2437 void ProfileSyncService::RequestStop(SyncStopDataFate data_fate) {
2438 sync_prefs_.SetSyncRequested(false);
2439 StopImpl(data_fate);
2442 bool ProfileSyncService::IsSyncRequested() const {
2443 return sync_prefs_.IsSyncRequested();
2446 SigninManagerBase* ProfileSyncService::signin() const {
2447 if (!signin_)
2448 return NULL;
2449 return signin_->GetOriginal();
2452 void ProfileSyncService::RequestStart() {
2453 DCHECK(profile_);
2454 sync_prefs_.SetSyncRequested(true);
2455 DCHECK(!signin_.get() || signin_->GetOriginal()->IsAuthenticated());
2456 startup_controller_->TryStart();
2459 void ProfileSyncService::ReconfigureDatatypeManager() {
2460 // If we haven't initialized yet, don't configure the DTM as it could cause
2461 // association to start before a Directory has even been created.
2462 if (backend_initialized_) {
2463 DCHECK(backend_.get());
2464 ConfigureDataTypeManager();
2465 } else if (HasUnrecoverableError()) {
2466 // There is nothing more to configure. So inform the listeners,
2467 NotifyObservers();
2469 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2470 << "Unrecoverable error.";
2471 } else {
2472 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2473 << "initialized";
2477 syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2478 const {
2479 syncer::ModelTypeSet types;
2480 for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2481 preference_providers_.begin();
2482 it != preference_providers_.end();
2483 ++it) {
2484 types.PutAll((*it)->GetPreferredDataTypes());
2486 return types;
2489 const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2490 const {
2491 return data_type_status_table_;
2494 void ProfileSyncService::OnInternalUnrecoverableError(
2495 const tracked_objects::Location& from_here,
2496 const std::string& message,
2497 bool delete_sync_database,
2498 UnrecoverableErrorReason reason) {
2499 DCHECK(!HasUnrecoverableError());
2500 unrecoverable_error_reason_ = reason;
2501 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2504 syncer::SyncManagerFactory::MANAGER_TYPE
2505 ProfileSyncService::GetManagerType() const {
2506 switch (backend_mode_) {
2507 case SYNC:
2508 return syncer::SyncManagerFactory::NORMAL;
2509 case BACKUP:
2510 return syncer::SyncManagerFactory::BACKUP;
2511 case ROLLBACK:
2512 return syncer::SyncManagerFactory::ROLLBACK;
2513 case IDLE:
2514 NOTREACHED();
2516 return syncer::SyncManagerFactory::NORMAL;
2519 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2520 return request_access_token_retry_timer_.IsRunning();
2523 std::string ProfileSyncService::GetAccessTokenForTest() const {
2524 return access_token_;
2527 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2528 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2531 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2532 return sessions_sync_manager_.get();
2535 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2536 return device_info_sync_service_.get();
2539 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2540 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED),
2541 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2542 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2544 ProfileSyncService::SyncTokenStatus
2545 ProfileSyncService::GetSyncTokenStatus() const {
2546 SyncTokenStatus status;
2547 status.connection_status_update_time = connection_status_update_time_;
2548 status.connection_status = connection_status_;
2549 status.token_request_time = token_request_time_;
2550 status.token_receive_time = token_receive_time_;
2551 status.last_get_token_error = last_get_token_error_;
2552 if (request_access_token_retry_timer_.IsRunning())
2553 status.next_token_request_time = next_token_request_time_;
2554 return status;
2557 void ProfileSyncService::OverrideNetworkResourcesForTest(
2558 scoped_ptr<syncer::NetworkResources> network_resources) {
2559 network_resources_ = network_resources.Pass();
2562 bool ProfileSyncService::HasSyncingBackend() const {
2563 return backend_mode_ != SYNC ? false : backend_ != NULL;
2566 void ProfileSyncService::UpdateFirstSyncTimePref() {
2567 if (!IsSignedIn()) {
2568 // Clear if user's not signed in and rollback is done.
2569 if (backend_mode_ != ROLLBACK)
2570 sync_prefs_.ClearFirstSyncTime();
2571 } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2572 backend_mode_ == SYNC) {
2573 // Set if not set before and it's syncing now.
2574 sync_prefs_.SetFirstSyncTime(base::Time::Now());
2578 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2579 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2580 if (first_sync_time.is_null())
2581 return;
2583 clear_browsing_data_.Run(browsing_data_remover_observer_,
2584 profile_,
2585 first_sync_time,
2586 base::Time::Now());
2589 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2590 BrowsingDataRemover::Observer* observer) {
2591 browsing_data_remover_observer_ = observer;
2594 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2595 base::Callback<void(BrowsingDataRemover::Observer* observer,
2596 Profile*,
2597 base::Time,
2598 base::Time)> c) {
2599 clear_browsing_data_ = c;
2602 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2603 DCHECK_EQ(backend_mode_, SYNC);
2605 #if defined(ENABLE_PRE_SYNC_BACKUP)
2606 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
2607 // Check backup once a day.
2608 if (!last_backup_time_ &&
2609 (last_synced_time.is_null() ||
2610 base::Time::Now() - last_synced_time >=
2611 base::TimeDelta::FromDays(1))) {
2612 // If sync thread is set, need to serialize check on sync thread after
2613 // closing backup DB.
2614 if (sync_thread_) {
2615 sync_thread_->task_runner()->PostTask(
2616 FROM_HERE,
2617 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2618 profile_->GetPath().Append(kSyncBackupDataFolderName),
2619 base::ThreadTaskRunnerHandle::Get(),
2620 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2621 weak_factory_.GetWeakPtr())));
2622 } else {
2623 content::BrowserThread::PostTask(
2624 content::BrowserThread::FILE, FROM_HERE,
2625 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2626 profile_->GetPath().Append(kSyncBackupDataFolderName),
2627 base::ThreadTaskRunnerHandle::Get(),
2628 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2629 weak_factory_.GetWeakPtr())));
2632 #endif
2635 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2636 last_backup_time_.reset(new base::Time(backup_time));
2638 DCHECK(device_info_sync_service_);
2639 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2642 void ProfileSyncService::TryStartSyncAfterBackup() {
2643 startup_controller_->Reset(GetRegisteredDataTypes());
2644 startup_controller_->TryStart();
2647 void ProfileSyncService::CleanUpBackup() {
2648 sync_prefs_.ClearFirstSyncTime();
2649 profile_->GetIOTaskRunner()->PostTask(
2650 FROM_HERE,
2651 base::Bind(base::IgnoreResult(base::DeleteFile),
2652 profile_->GetPath().Append(kSyncBackupDataFolderName),
2653 true));
2656 bool ProfileSyncService::NeedBackup() const {
2657 return need_backup_;
2660 base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2661 return device_info_sync_service_->GetLocalDeviceBackupTime();
2664 void ProfileSyncService::FlushDirectory() const {
2665 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2666 // If sync is not initialized yet, we fail silently.
2667 if (backend_initialized_)
2668 backend_->FlushDirectory();
2671 base::FilePath ProfileSyncService::GetDirectoryPathForTest() const {
2672 return directory_path_;
2675 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2676 if (sync_thread_) {
2677 return sync_thread_->message_loop();
2678 } else if (backend_) {
2679 return backend_->GetSyncLoopForTesting();
2680 } else {
2681 return NULL;
2685 void ProfileSyncService::RefreshTypesForTest(syncer::ModelTypeSet types) {
2686 if (backend_initialized_)
2687 backend_->RefreshTypesForTest(types);
2690 void ProfileSyncService::RemoveClientFromServer() const {
2691 if (!backend_initialized_) return;
2692 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
2693 std::string birthday;
2694 syncer::UserShare* user_share = GetUserShare();
2695 if (user_share && user_share->directory.get()) {
2696 birthday = user_share->directory->store_birthday();
2698 if (!access_token_.empty() && !cache_guid.empty() && !birthday.empty()) {
2699 sync_stopped_reporter_->ReportSyncStopped(
2700 access_token_, cache_guid, birthday);
2704 void ProfileSyncService::OnMemoryPressure(
2705 base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
2706 if (memory_pressure_level ==
2707 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL) {
2708 sync_prefs_.SetMemoryPressureWarningCount(
2709 sync_prefs_.GetMemoryPressureWarningCount() + 1);
2713 void ProfileSyncService::ReportPreviousSessionMemoryWarningCount() {
2714 int warning_received = sync_prefs_.GetMemoryPressureWarningCount();
2716 if (-1 != warning_received) {
2717 // -1 means it is new client.
2718 if (!sync_prefs_.DidSyncShutdownCleanly()) {
2719 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeUncleanShutdown",
2720 warning_received);
2721 } else {
2722 UMA_HISTOGRAM_COUNTS("Sync.MemoryPressureWarningBeforeCleanShutdown",
2723 warning_received);
2726 sync_prefs_.SetMemoryPressureWarningCount(0);
2727 // Will set to true during a clean shutdown, so crash or something else will
2728 // remain this as false.
2729 sync_prefs_.SetCleanShutdown(false);