Add ENABLE_MEDIA_ROUTER define to builds other than Android and iOS.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service.cc
blob9b09cd185962fc681ea9b89365bcb6d0e7101694
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/sync/profile_sync_service.h"
7 #include <cstddef>
8 #include <map>
9 #include <vector>
11 #include "base/basictypes.h"
12 #include "base/bind.h"
13 #include "base/bind_helpers.h"
14 #include "base/callback.h"
15 #include "base/command_line.h"
16 #include "base/compiler_specific.h"
17 #include "base/files/file_util.h"
18 #include "base/logging.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/message_loop/message_loop.h"
21 #include "base/metrics/histogram.h"
22 #include "base/profiler/scoped_tracker.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/threading/thread_restrictions.h"
26 #include "build/build_config.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/browsing_data/browsing_data_helper.h"
29 #include "chrome/browser/chrome_notification_types.h"
30 #include "chrome/browser/defaults.h"
31 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
32 #include "chrome/browser/net/chrome_cookie_notification_details.h"
33 #include "chrome/browser/password_manager/password_store_factory.h"
34 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
35 #include "chrome/browser/prefs/pref_service_syncable.h"
36 #include "chrome/browser/profiles/profile.h"
37 #include "chrome/browser/signin/about_signin_internals_factory.h"
38 #include "chrome/browser/signin/chrome_signin_client_factory.h"
39 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
40 #include "chrome/browser/signin/signin_manager_factory.h"
41 #include "chrome/browser/sync/backend_migrator.h"
42 #include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h"
43 #include "chrome/browser/sync/glue/favicon_cache.h"
44 #include "chrome/browser/sync/glue/sync_backend_host.h"
45 #include "chrome/browser/sync/glue/sync_backend_host_impl.h"
46 #include "chrome/browser/sync/glue/sync_start_util.h"
47 #include "chrome/browser/sync/glue/typed_url_data_type_controller.h"
48 #include "chrome/browser/sync/profile_sync_components_factory_impl.h"
49 #include "chrome/browser/sync/sessions/notification_service_sessions_router.h"
50 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
51 #include "chrome/browser/sync/sync_error_controller.h"
52 #include "chrome/browser/sync/sync_stopped_reporter.h"
53 #include "chrome/browser/sync/sync_type_preference_provider.h"
54 #include "chrome/browser/ui/browser.h"
55 #include "chrome/browser/ui/browser_list.h"
56 #include "chrome/browser/ui/browser_window.h"
57 #include "chrome/browser/ui/global_error/global_error_service.h"
58 #include "chrome/browser/ui/global_error/global_error_service_factory.h"
59 #include "chrome/common/chrome_switches.h"
60 #include "chrome/common/chrome_version_info.h"
61 #include "chrome/common/pref_names.h"
62 #include "chrome/common/url_constants.h"
63 #include "chrome/grit/generated_resources.h"
64 #include "components/autofill/core/common/autofill_pref_names.h"
65 #include "components/invalidation/invalidation_service.h"
66 #include "components/invalidation/profile_invalidation_provider.h"
67 #include "components/password_manager/core/browser/password_store.h"
68 #include "components/pref_registry/pref_registry_syncable.h"
69 #include "components/signin/core/browser/about_signin_internals.h"
70 #include "components/signin/core/browser/profile_oauth2_token_service.h"
71 #include "components/signin/core/browser/signin_manager.h"
72 #include "components/signin/core/browser/signin_metrics.h"
73 #include "components/sync_driver/change_processor.h"
74 #include "components/sync_driver/data_type_controller.h"
75 #include "components/sync_driver/device_info.h"
76 #include "components/sync_driver/pref_names.h"
77 #include "components/sync_driver/system_encryptor.h"
78 #include "components/sync_driver/user_selectable_sync_type.h"
79 #include "content/public/browser/browser_thread.h"
80 #include "content/public/browser/notification_details.h"
81 #include "content/public/browser/notification_service.h"
82 #include "content/public/browser/notification_source.h"
83 #include "net/cookies/cookie_monster.h"
84 #include "net/url_request/url_request_context_getter.h"
85 #include "sync/api/sync_error.h"
86 #include "sync/internal_api/public/configure_reason.h"
87 #include "sync/internal_api/public/http_bridge_network_resources.h"
88 #include "sync/internal_api/public/network_resources.h"
89 #include "sync/internal_api/public/sessions/type_debug_info_observer.h"
90 #include "sync/internal_api/public/shutdown_reason.h"
91 #include "sync/internal_api/public/sync_context_proxy.h"
92 #include "sync/internal_api/public/sync_encryption_handler.h"
93 #include "sync/internal_api/public/util/experiments.h"
94 #include "sync/internal_api/public/util/sync_db_util.h"
95 #include "sync/internal_api/public/util/sync_string_conversions.h"
96 #include "sync/js/js_event_details.h"
97 #include "sync/protocol/sync.pb.h"
98 #include "sync/syncable/directory.h"
99 #include "sync/util/cryptographer.h"
100 #include "ui/base/l10n/l10n_util.h"
101 #include "ui/base/l10n/time_format.h"
103 #if defined(OS_ANDROID)
104 #include "sync/internal_api/public/read_transaction.h"
105 #endif
107 using browser_sync::NotificationServiceSessionsRouter;
108 using browser_sync::ProfileSyncServiceStartBehavior;
109 using browser_sync::SessionsSyncManager;
110 using browser_sync::SyncBackendHost;
111 using sync_driver::ChangeProcessor;
112 using sync_driver::DataTypeController;
113 using sync_driver::DataTypeManager;
114 using sync_driver::DataTypeStatusTable;
115 using sync_driver::DeviceInfoSyncService;
116 using syncer::ModelType;
117 using syncer::ModelTypeSet;
118 using syncer::JsBackend;
119 using syncer::JsController;
120 using syncer::JsEventDetails;
121 using syncer::JsEventHandler;
122 using syncer::ModelSafeRoutingInfo;
123 using syncer::SyncCredentials;
124 using syncer::SyncProtocolError;
125 using syncer::WeakHandle;
127 typedef GoogleServiceAuthError AuthError;
129 const char* ProfileSyncService::kSyncServerUrl =
130 "https://clients4.google.com/chrome-sync";
132 const char* ProfileSyncService::kDevServerUrl =
133 "https://clients4.google.com/chrome-sync/dev";
135 const char kSyncUnrecoverableErrorHistogram[] =
136 "Sync.UnrecoverableErrors";
138 const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = {
139 // Number of initial errors (in sequence) to ignore before applying
140 // exponential back-off rules.
143 // Initial delay for exponential back-off in ms.
144 2000,
146 // Factor by which the waiting time will be multiplied.
149 // Fuzzing percentage. ex: 10% will spread requests randomly
150 // between 90%-100% of the calculated time.
151 0.2, // 20%
153 // Maximum amount of time we are willing to delay our request in ms.
154 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry
155 // RequestAccessToken on connection state change after backoff
156 1000 * 3600 * 4, // 4 hours.
158 // Time to keep an entry from being discarded even when it
159 // has no significant state, -1 to never discard.
162 // Don't use initial delay unless the last request was an error.
163 false,
166 static const base::FilePath::CharType kSyncDataFolderName[] =
167 FILE_PATH_LITERAL("Sync Data");
169 static const base::FilePath::CharType kSyncBackupDataFolderName[] =
170 FILE_PATH_LITERAL("Sync Data Backup");
172 namespace {
174 void ClearBrowsingData(BrowsingDataRemover::Observer* observer,
175 Profile* profile,
176 base::Time start,
177 base::Time end) {
178 // BrowsingDataRemover deletes itself when it's done.
179 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(
180 profile, start, end);
181 if (observer)
182 remover->AddObserver(observer);
183 remover->Remove(BrowsingDataRemover::REMOVE_ALL,
184 BrowsingDataHelper::ALL);
186 scoped_refptr<password_manager::PasswordStore> password =
187 PasswordStoreFactory::GetForProfile(profile,
188 ServiceAccessType::EXPLICIT_ACCESS);
189 password->RemoveLoginsSyncedBetween(start, end);
192 // Perform the actual sync data folder deletion.
193 // This should only be called on the sync thread.
194 void DeleteSyncDataFolder(const base::FilePath& directory_path) {
195 if (base::DirectoryExists(directory_path)) {
196 if (!base::DeleteFile(directory_path, true))
197 LOG(DFATAL) << "Could not delete the Sync Data folder.";
201 } // anonymous namespace
203 bool ShouldShowActionOnUI(
204 const syncer::SyncProtocolError& error) {
205 return (error.action != syncer::UNKNOWN_ACTION &&
206 error.action != syncer::DISABLE_SYNC_ON_CLIENT &&
207 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT);
210 ProfileSyncService::ProfileSyncService(
211 scoped_ptr<ProfileSyncComponentsFactory> factory,
212 Profile* profile,
213 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper,
214 ProfileOAuth2TokenService* oauth2_token_service,
215 ProfileSyncServiceStartBehavior start_behavior)
216 : OAuth2TokenService::Consumer("sync"),
217 last_auth_error_(AuthError::AuthErrorNone()),
218 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED),
219 factory_(factory.Pass()),
220 profile_(profile),
221 sync_prefs_(profile_->GetPrefs()),
222 sync_service_url_(
223 GetSyncServiceURL(*base::CommandLine::ForCurrentProcess())),
224 is_first_time_sync_configure_(false),
225 backend_initialized_(false),
226 sync_disabled_by_admin_(false),
227 is_auth_in_progress_(false),
228 signin_(signin_wrapper.Pass()),
229 unrecoverable_error_reason_(ERROR_REASON_UNSET),
230 expect_sync_configuration_aborted_(false),
231 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()),
232 encrypt_everything_allowed_(true),
233 encrypt_everything_(false),
234 encryption_pending_(false),
235 configure_status_(DataTypeManager::UNKNOWN),
236 oauth2_token_service_(oauth2_token_service),
237 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy),
238 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED),
239 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()),
240 network_resources_(new syncer::HttpBridgeNetworkResources),
241 backend_mode_(IDLE),
242 need_backup_(false),
243 backup_finished_(false),
244 clear_browsing_data_(base::Bind(&ClearBrowsingData)),
245 browsing_data_remover_observer_(NULL),
246 sync_stopped_reporter_(
247 new browser_sync::SyncStoppedReporter(
248 sync_service_url_,
249 profile_->GetRequestContext(),
250 browser_sync::SyncStoppedReporter::ResultCallback())),
251 weak_factory_(this),
252 startup_controller_weak_factory_(this) {
253 DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
254 DCHECK(profile);
255 startup_controller_.reset(new browser_sync::StartupController(
256 start_behavior,
257 oauth2_token_service,
258 &sync_prefs_,
259 signin_.get(),
260 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
261 startup_controller_weak_factory_.GetWeakPtr(),
262 SYNC)));
263 backup_rollback_controller_.reset(new browser_sync::BackupRollbackController(
264 &sync_prefs_,
265 signin_.get(),
266 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
267 startup_controller_weak_factory_.GetWeakPtr(),
268 BACKUP),
269 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents,
270 startup_controller_weak_factory_.GetWeakPtr(),
271 ROLLBACK)));
272 syncer::SyncableService::StartSyncFlare flare(
273 sync_start_util::GetFlareForSyncableService(profile->GetPath()));
274 scoped_ptr<browser_sync::LocalSessionEventRouter> router(
275 new NotificationServiceSessionsRouter(profile, flare));
277 DCHECK(factory_.get());
278 local_device_ = factory_->CreateLocalDeviceInfoProvider();
279 sessions_sync_manager_.reset(
280 new SessionsSyncManager(profile, local_device_.get(), router.Pass()));
281 device_info_sync_service_.reset(
282 new DeviceInfoSyncService(local_device_.get()));
285 ProfileSyncService::~ProfileSyncService() {
286 sync_prefs_.RemoveSyncPrefObserver(this);
287 // Shutdown() should have been called before destruction.
288 CHECK(!backend_initialized_);
291 bool ProfileSyncService::IsSyncEnabledAndLoggedIn() {
292 // Exit if sync is disabled.
293 if (IsManaged() || sync_prefs_.IsStartSuppressed())
294 return false;
296 // Sync is logged in if there is a non-empty effective username.
297 return !signin_->GetEffectiveUsername().empty();
300 bool ProfileSyncService::IsOAuthRefreshTokenAvailable() {
301 if (!oauth2_token_service_)
302 return false;
304 return oauth2_token_service_->RefreshTokenIsAvailable(
305 signin_->GetAccountIdToUse());
308 void ProfileSyncService::Initialize() {
309 // We clear this here (vs Shutdown) because we want to remember that an error
310 // happened on shutdown so we can display details (message, location) about it
311 // in about:sync.
312 ClearStaleErrors();
314 sync_prefs_.AddSyncPrefObserver(this);
316 // For now, the only thing we can do through policy is to turn sync off.
317 if (IsManaged()) {
318 DisableForUser();
319 return;
322 RegisterAuthNotifications();
324 if (!HasSyncSetupCompleted() || signin_->GetEffectiveUsername().empty()) {
325 // Clean up in case of previous crash / setup abort / signout.
326 DisableForUser();
329 TrySyncDatatypePrefRecovery();
331 #if defined(OS_CHROMEOS)
332 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken();
333 if (bootstrap_token.empty()) {
334 sync_prefs_.SetEncryptionBootstrapToken(
335 sync_prefs_.GetSpareBootstrapToken());
337 #endif
339 #if !defined(OS_ANDROID)
340 DCHECK(sync_error_controller_ == NULL)
341 << "Initialize() called more than once.";
342 sync_error_controller_.reset(new SyncErrorController(this));
343 AddObserver(sync_error_controller_.get());
344 #endif
346 bool running_rollback = false;
347 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
348 // Backup is needed if user's not signed in or signed in but previous
349 // backup didn't finish, i.e. backend didn't switch from backup to sync.
350 need_backup_ = signin_->GetEffectiveUsername().empty() ||
351 sync_prefs_.GetFirstSyncTime().is_null();
353 // Try to resume rollback if it didn't finish in last session.
354 running_rollback = backup_rollback_controller_->StartRollback();
355 } else {
356 need_backup_ = false;
359 #if defined(ENABLE_PRE_SYNC_BACKUP)
360 if (!running_rollback && signin_->GetEffectiveUsername().empty()) {
361 CleanUpBackup();
363 #else
364 DCHECK(!running_rollback);
365 #endif
367 startup_controller_->Reset(GetRegisteredDataTypes());
368 startup_controller_->TryStart();
371 void ProfileSyncService::TrySyncDatatypePrefRecovery() {
372 DCHECK(!backend_initialized());
373 if (!HasSyncSetupCompleted())
374 return;
376 // There was a bug where OnUserChoseDatatypes was not properly called on
377 // configuration (see crbug.com/154940). We detect this by checking whether
378 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has
379 // completed, it means sync was not properly configured, so we manually
380 // set kSyncKeepEverythingSynced.
381 PrefService* const pref_service = profile_->GetPrefs();
382 if (!pref_service)
383 return;
384 if (GetPreferredDataTypes().Size() > 1)
385 return;
387 const PrefService::Preference* keep_everything_synced =
388 pref_service->FindPreference(
389 sync_driver::prefs::kSyncKeepEverythingSynced);
390 // This will be false if the preference was properly set or if it's controlled
391 // by policy.
392 if (!keep_everything_synced->IsDefaultValue())
393 return;
395 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred
396 // types now, before we configure.
397 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1);
398 sync_prefs_.SetKeepEverythingSynced(true);
399 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
402 void ProfileSyncService::StartSyncingWithServer() {
403 if (backend_)
404 backend_->StartSyncingWithServer();
407 void ProfileSyncService::RegisterAuthNotifications() {
408 oauth2_token_service_->AddObserver(this);
409 if (signin())
410 signin()->AddObserver(this);
413 void ProfileSyncService::UnregisterAuthNotifications() {
414 if (signin())
415 signin()->RemoveObserver(this);
416 oauth2_token_service_->RemoveObserver(this);
419 void ProfileSyncService::RegisterDataTypeController(
420 DataTypeController* data_type_controller) {
421 DCHECK_EQ(
422 directory_data_type_controllers_.count(data_type_controller->type()),
423 0U);
424 DCHECK(!GetRegisteredNonBlockingDataTypes().Has(
425 data_type_controller->type()));
426 directory_data_type_controllers_[data_type_controller->type()] =
427 data_type_controller;
430 void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) {
431 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U)
432 << "Duplicate registration of type " << ModelTypeToString(type);
434 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is
435 // fixed and we have some way of telling whether or not this type should be
436 // enabled.
437 non_blocking_data_type_manager_.RegisterType(type, false);
440 void ProfileSyncService::InitializeNonBlockingType(
441 syncer::ModelType type,
442 const scoped_refptr<base::SequencedTaskRunner>& task_runner,
443 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) {
444 non_blocking_data_type_manager_.InitializeType(
445 type, task_runner, type_sync_proxy);
448 bool ProfileSyncService::IsDataTypeControllerRunning(
449 syncer::ModelType type) const {
450 DataTypeController::TypeMap::const_iterator iter =
451 directory_data_type_controllers_.find(type);
452 if (iter == directory_data_type_controllers_.end()) {
453 return false;
455 return iter->second->state() == DataTypeController::RUNNING;
458 browser_sync::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() {
459 if (!IsDataTypeControllerRunning(syncer::SESSIONS))
460 return NULL;
461 return sessions_sync_manager_.get();
464 browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() {
465 return sessions_sync_manager_->GetFaviconCache();
468 browser_sync::SyncedWindowDelegatesGetter*
469 ProfileSyncService::GetSyncedWindowDelegatesGetter() const {
470 return sessions_sync_manager_->GetSyncedWindowDelegatesGetter();
473 sync_driver::DeviceInfoTracker* ProfileSyncService::GetDeviceInfoTracker()
474 const {
475 return device_info_sync_service_.get();
478 sync_driver::LocalDeviceInfoProvider*
479 ProfileSyncService::GetLocalDeviceInfoProvider() {
480 return local_device_.get();
483 void ProfileSyncService::GetDataTypeControllerStates(
484 DataTypeController::StateMap* state_map) const {
485 for (DataTypeController::TypeMap::const_iterator iter =
486 directory_data_type_controllers_.begin();
487 iter != directory_data_type_controllers_.end();
488 ++iter)
489 (*state_map)[iter->first] = iter->second.get()->state();
492 SyncCredentials ProfileSyncService::GetCredentials() {
493 SyncCredentials credentials;
494 if (backend_mode_ == SYNC) {
495 credentials.email = signin_->GetEffectiveUsername();
496 DCHECK(!credentials.email.empty());
497 credentials.sync_token = access_token_;
499 if (credentials.sync_token.empty())
500 credentials.sync_token = "credentials_lost";
502 credentials.scope_set.insert(signin_->GetSyncScopeToUse());
505 return credentials;
508 bool ProfileSyncService::ShouldDeleteSyncFolder() {
509 switch (backend_mode_) {
510 case SYNC:
511 return !HasSyncSetupCompleted();
512 case BACKUP:
513 return true;
514 case ROLLBACK:
515 return false;
516 case IDLE:
517 NOTREACHED();
518 return true;
520 return true;
523 void ProfileSyncService::InitializeBackend(bool delete_stale_data) {
524 if (!backend_) {
525 NOTREACHED();
526 return;
529 SyncCredentials credentials = GetCredentials();
531 scoped_refptr<net::URLRequestContextGetter> request_context_getter(
532 profile_->GetRequestContext());
534 if (backend_mode_ == SYNC && delete_stale_data)
535 ClearStaleErrors();
537 scoped_ptr<syncer::UnrecoverableErrorHandler>
538 backend_unrecoverable_error_handler(
539 new browser_sync::BackendUnrecoverableErrorHandler(
540 MakeWeakHandle(weak_factory_.GetWeakPtr())));
542 backend_->Initialize(
543 this,
544 sync_thread_.Pass(),
545 GetJsEventHandler(),
546 sync_service_url_,
547 credentials,
548 delete_stale_data,
549 scoped_ptr<syncer::SyncManagerFactory>(
550 new syncer::SyncManagerFactory(GetManagerType())).Pass(),
551 backend_unrecoverable_error_handler.Pass(),
552 &browser_sync::ChromeReportUnrecoverableError,
553 network_resources_.get());
556 bool ProfileSyncService::IsEncryptedDatatypeEnabled() const {
557 if (encryption_pending())
558 return true;
559 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
560 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes();
561 DCHECK(encrypted_types.Has(syncer::PASSWORDS));
562 return !Intersection(preferred_types, encrypted_types).Empty();
565 void ProfileSyncService::OnProtocolEvent(
566 const syncer::ProtocolEvent& event) {
567 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver,
568 protocol_event_observers_,
569 OnProtocolEvent(event));
572 void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated(
573 syncer::ModelType type,
574 const syncer::CommitCounters& counters) {
575 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
576 type_debug_info_observers_,
577 OnCommitCountersUpdated(type, counters));
580 void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated(
581 syncer::ModelType type,
582 const syncer::UpdateCounters& counters) {
583 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
584 type_debug_info_observers_,
585 OnUpdateCountersUpdated(type, counters));
588 void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated(
589 syncer::ModelType type,
590 const syncer::StatusCounters& counters) {
591 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver,
592 type_debug_info_observers_,
593 OnStatusCountersUpdated(type, counters));
596 void ProfileSyncService::OnDataTypeRequestsSyncStartup(
597 syncer::ModelType type) {
598 DCHECK(syncer::UserTypes().Has(type));
599 if (backend_.get()) {
600 DVLOG(1) << "A data type requested sync startup, but it looks like "
601 "something else beat it to the punch.";
602 return;
605 if (!GetPreferredDataTypes().Has(type)) {
606 // We can get here as datatype SyncableServices are typically wired up
607 // to the native datatype even if sync isn't enabled.
608 DVLOG(1) << "Dropping sync startup request because type "
609 << syncer::ModelTypeToString(type) << "not enabled.";
610 return;
613 startup_controller_->OnDataTypeRequestsSyncStartup(type);
616 void ProfileSyncService::StartUpSlowBackendComponents(
617 ProfileSyncService::BackendMode mode) {
618 DCHECK_NE(IDLE, mode);
619 if (backend_mode_ == mode) {
620 return;
623 // Backend mode transition rules:
624 // * can transit from IDLE to any other non-IDLE mode.
625 // * forbidden to transit from SYNC to any other mode, i.e. SYNC backend must
626 // be explicitly shut down before backup/rollback starts.
627 // * can not transit out of ROLLBACK mode until rollback is finished
628 // (successfully or unsuccessfully).
629 // * can not transit out of BACKUP mode until backup is finished
630 // (successfully or unsuccessfully).
631 // * if backup is needed, can only transit to SYNC if backup is finished,
633 if (backend_mode_ == SYNC) {
634 LOG(DFATAL) << "Shouldn't switch from mode SYNC to mode " << mode;
635 return;
638 if (backend_mode_ == ROLLBACK ||
639 (backend_mode_ == BACKUP && !backup_finished_)) {
640 // Wait for rollback/backup to finish before start new backend.
641 return;
644 if (mode == SYNC && NeedBackup() && !backup_finished_) {
645 if (backend_mode_ != BACKUP)
646 backup_rollback_controller_->StartBackup();
647 return;
650 DVLOG(1) << "Start backend mode: " << mode;
652 if (backend_) {
653 if (mode == SYNC)
654 ShutdownImpl(syncer::SWITCH_MODE_SYNC);
655 else
656 ShutdownImpl(syncer::STOP_SYNC);
659 backend_mode_ = mode;
661 if (backend_mode_ == BACKUP)
662 backup_start_time_ = base::Time::Now();
664 if (backend_mode_ == SYNC && !backup_start_time_.is_null()) {
665 UMA_HISTOGRAM_MEDIUM_TIMES("Sync.FirstSyncDelayByBackup",
666 base::Time::Now() - backup_start_time_);
667 backup_start_time_ = base::Time();
670 if (backend_mode_ == ROLLBACK)
671 ClearBrowsingDataSinceFirstSync();
672 else if (backend_mode_ == SYNC)
673 CheckSyncBackupIfNeeded();
675 base::FilePath sync_folder = backend_mode_ == SYNC ?
676 base::FilePath(kSyncDataFolderName) :
677 base::FilePath(kSyncBackupDataFolderName);
679 invalidation::InvalidationService* invalidator = NULL;
680 if (backend_mode_ == SYNC) {
681 invalidation::ProfileInvalidationProvider* provider =
682 invalidation::ProfileInvalidationProviderFactory::GetForProfile(
683 profile_);
684 if (provider)
685 invalidator = provider->GetInvalidationService();
688 directory_path_ = profile_->GetPath().Append(sync_folder);
690 backend_.reset(
691 factory_->CreateSyncBackendHost(
692 profile_->GetDebugName(),
693 profile_,
694 invalidator,
695 sync_prefs_.AsWeakPtr(),
696 sync_folder));
698 // Initialize the backend. Every time we start up a new SyncBackendHost,
699 // we'll want to start from a fresh SyncDB, so delete any old one that might
700 // be there.
701 InitializeBackend(ShouldDeleteSyncFolder());
703 UpdateFirstSyncTimePref();
706 void ProfileSyncService::OnGetTokenSuccess(
707 const OAuth2TokenService::Request* request,
708 const std::string& access_token,
709 const base::Time& expiration_time) {
710 DCHECK_EQ(access_token_request_, request);
711 access_token_request_.reset();
712 access_token_ = access_token;
713 token_receive_time_ = base::Time::Now();
714 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone();
716 if (sync_prefs_.SyncHasAuthError()) {
717 sync_prefs_.SetSyncAuthError(false);
718 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
719 AUTH_ERROR_FIXED,
720 AUTH_ERROR_LIMIT);
723 if (HasSyncingBackend())
724 backend_->UpdateCredentials(GetCredentials());
725 else
726 startup_controller_->TryStart();
729 void ProfileSyncService::OnGetTokenFailure(
730 const OAuth2TokenService::Request* request,
731 const GoogleServiceAuthError& error) {
732 DCHECK_EQ(access_token_request_, request);
733 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE);
734 access_token_request_.reset();
735 last_get_token_error_ = error;
736 switch (error.state()) {
737 case GoogleServiceAuthError::CONNECTION_FAILED:
738 case GoogleServiceAuthError::REQUEST_CANCELED:
739 case GoogleServiceAuthError::SERVICE_ERROR:
740 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: {
741 // Transient error. Retry after some time.
742 request_access_token_backoff_.InformOfRequest(false);
743 next_token_request_time_ = base::Time::Now() +
744 request_access_token_backoff_.GetTimeUntilRelease();
745 request_access_token_retry_timer_.Start(
746 FROM_HERE,
747 request_access_token_backoff_.GetTimeUntilRelease(),
748 base::Bind(&ProfileSyncService::RequestAccessToken,
749 weak_factory_.GetWeakPtr()));
750 NotifyObservers();
751 break;
753 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: {
754 if (!sync_prefs_.SyncHasAuthError()) {
755 sync_prefs_.SetSyncAuthError(true);
756 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError",
757 AUTH_ERROR_ENCOUNTERED,
758 AUTH_ERROR_LIMIT);
760 // Fallthrough.
762 default: {
763 if (error.state() != GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS) {
764 LOG(ERROR) << "Unexpected persistent error: " << error.ToString();
766 // Show error to user.
767 UpdateAuthErrorState(error);
772 void ProfileSyncService::OnRefreshTokenAvailable(
773 const std::string& account_id) {
774 // TODO(robliao): Remove ScopedTracker below once https://crbug.com/422460 is
775 // fixed.
776 tracked_objects::ScopedTracker tracking_profile(
777 FROM_HERE_WITH_EXPLICIT_FUNCTION(
778 "422460 ProfileSyncService::OnRefreshTokenAvailable"));
780 if (account_id == signin_->GetAccountIdToUse())
781 OnRefreshTokensLoaded();
784 void ProfileSyncService::OnRefreshTokenRevoked(
785 const std::string& account_id) {
786 if (!IsOAuthRefreshTokenAvailable()) {
787 access_token_.clear();
788 // The additional check around IsOAuthRefreshTokenAvailable() above
789 // prevents us sounding the alarm if we actually have a valid token but
790 // a refresh attempt failed for any variety of reasons
791 // (e.g. flaky network). It's possible the token we do have is also
792 // invalid, but in that case we should already have (or can expect) an
793 // auth error sent from the sync backend.
794 UpdateAuthErrorState(
795 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED));
799 void ProfileSyncService::OnRefreshTokensLoaded() {
800 // This notification gets fired when OAuth2TokenService loads the tokens
801 // from storage.
802 // Initialize the backend if sync is enabled. If the sync token was
803 // not loaded, GetCredentials() will generate invalid credentials to
804 // cause the backend to generate an auth error (crbug.com/121755).
805 if (HasSyncingBackend()) {
806 RequestAccessToken();
807 } else {
808 startup_controller_->TryStart();
812 void ProfileSyncService::Shutdown() {
813 UnregisterAuthNotifications();
815 ShutdownImpl(syncer::BROWSER_SHUTDOWN);
816 if (sync_error_controller_) {
817 // Destroy the SyncErrorController when the service shuts down for good.
818 RemoveObserver(sync_error_controller_.get());
819 sync_error_controller_.reset();
822 if (sync_thread_)
823 sync_thread_->Stop();
826 void ProfileSyncService::ShutdownImpl(syncer::ShutdownReason reason) {
827 if (!backend_) {
828 if (reason == syncer::ShutdownReason::DISABLE_SYNC && sync_thread_) {
829 // If the backend is already shut down when a DISABLE_SYNC happens,
830 // the data directory needs to be cleaned up here.
831 sync_thread_->message_loop()->PostTask(FROM_HERE,
832 base::Bind(&DeleteSyncDataFolder, directory_path_));
834 return;
837 if (reason == syncer::ShutdownReason::STOP_SYNC
838 || reason == syncer::ShutdownReason::DISABLE_SYNC) {
839 RemoveClientFromServer();
842 non_blocking_data_type_manager_.DisconnectSyncBackend();
844 // First, we spin down the backend to stop change processing as soon as
845 // possible.
846 base::Time shutdown_start_time = base::Time::Now();
847 backend_->StopSyncingForShutdown();
849 // Stop all data type controllers, if needed. Note that until Stop
850 // completes, it is possible in theory to have a ChangeProcessor apply a
851 // change from a native model. In that case, it will get applied to the sync
852 // database (which doesn't get destroyed until we destroy the backend below)
853 // as an unsynced change. That will be persisted, and committed on restart.
854 if (directory_data_type_manager_) {
855 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) {
856 // When aborting as part of shutdown, we should expect an aborted sync
857 // configure result, else we'll dcheck when we try to read the sync error.
858 expect_sync_configuration_aborted_ = true;
859 directory_data_type_manager_->Stop();
861 directory_data_type_manager_.reset();
864 // Shutdown the migrator before the backend to ensure it doesn't pull a null
865 // snapshot.
866 migrator_.reset();
867 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>());
869 // Move aside the backend so nobody else tries to use it while we are
870 // shutting it down.
871 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release());
872 if (doomed_backend) {
873 sync_thread_ = doomed_backend->Shutdown(reason);
874 doomed_backend.reset();
876 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time;
877 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time);
879 weak_factory_.InvalidateWeakPtrs();
881 if (backend_mode_ == SYNC)
882 startup_controller_->Reset(GetRegisteredDataTypes());
884 // Don't let backup block sync regardless backup succeeded or not.
885 if (backend_mode_ == BACKUP)
886 backup_finished_ = true;
888 // Sync could be blocked by rollback/backup. Post task to check whether sync
889 // should start after shutting down rollback/backup backend.
890 if ((backend_mode_ == ROLLBACK || backend_mode_ == BACKUP) &&
891 reason != syncer::SWITCH_MODE_SYNC &&
892 reason != syncer::BROWSER_SHUTDOWN) {
893 base::MessageLoop::current()->PostTask(
894 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
895 startup_controller_weak_factory_.GetWeakPtr()));
898 // Clear various flags.
899 backend_mode_ = IDLE;
900 expect_sync_configuration_aborted_ = false;
901 is_auth_in_progress_ = false;
902 backend_initialized_ = false;
903 cached_passphrase_.clear();
904 encryption_pending_ = false;
905 encrypt_everything_ = false;
906 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes();
907 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
908 request_access_token_retry_timer_.Stop();
909 // Revert to "no auth error".
910 if (last_auth_error_.state() != GoogleServiceAuthError::NONE)
911 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone());
913 NotifyObservers();
916 void ProfileSyncService::DisableForUser() {
917 // Clear prefs (including SyncSetupHasCompleted) before shutting down so
918 // PSS clients don't think we're set up while we're shutting down.
919 sync_prefs_.ClearPreferences();
920 ClearUnrecoverableError();
921 ShutdownImpl(syncer::DISABLE_SYNC);
924 bool ProfileSyncService::HasSyncSetupCompleted() const {
925 return sync_prefs_.HasSyncSetupCompleted();
928 void ProfileSyncService::SetSyncSetupCompleted() {
929 sync_prefs_.SetSyncSetupCompleted();
932 void ProfileSyncService::UpdateLastSyncedTime() {
933 sync_prefs_.SetLastSyncedTime(base::Time::Now());
936 void ProfileSyncService::NotifyObservers() {
937 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
938 OnStateChanged());
941 void ProfileSyncService::NotifySyncCycleCompleted() {
942 FOR_EACH_OBSERVER(sync_driver::SyncServiceObserver, observers_,
943 OnSyncCycleCompleted());
946 void ProfileSyncService::ClearStaleErrors() {
947 ClearUnrecoverableError();
948 last_actionable_error_ = SyncProtocolError();
949 // Clear the data type errors as well.
950 if (directory_data_type_manager_.get())
951 directory_data_type_manager_->ResetDataTypeErrors();
955 void ProfileSyncService::ClearUnrecoverableError() {
956 unrecoverable_error_reason_ = ERROR_REASON_UNSET;
957 unrecoverable_error_message_.clear();
958 unrecoverable_error_location_ = tracked_objects::Location();
961 // An invariant has been violated. Transition to an error state where we try
962 // to do as little work as possible, to avoid further corruption or crashes.
963 void ProfileSyncService::OnUnrecoverableError(
964 const tracked_objects::Location& from_here,
965 const std::string& message) {
966 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler
967 // interface are assumed to originate within the syncer.
968 unrecoverable_error_reason_ = ERROR_REASON_SYNCER;
969 OnUnrecoverableErrorImpl(from_here, message, true);
972 void ProfileSyncService::OnUnrecoverableErrorImpl(
973 const tracked_objects::Location& from_here,
974 const std::string& message,
975 bool delete_sync_database) {
976 DCHECK(HasUnrecoverableError());
977 unrecoverable_error_message_ = message;
978 unrecoverable_error_location_ = from_here;
980 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram,
981 unrecoverable_error_reason_,
982 ERROR_REASON_LIMIT);
983 std::string location;
984 from_here.Write(true, true, &location);
985 LOG(ERROR)
986 << "Unrecoverable error detected at " << location
987 << " -- ProfileSyncService unusable: " << message;
989 // Shut all data types down.
990 base::MessageLoop::current()->PostTask(FROM_HERE,
991 base::Bind(&ProfileSyncService::ShutdownImpl,
992 weak_factory_.GetWeakPtr(),
993 delete_sync_database ?
994 syncer::DISABLE_SYNC : syncer::STOP_SYNC));
997 void ProfileSyncService::ReenableDatatype(syncer::ModelType type) {
998 if (!backend_initialized_)
999 return;
1000 directory_data_type_manager_->ReenableType(type);
1003 void ProfileSyncService::UpdateBackendInitUMA(bool success) {
1004 if (backend_mode_ != SYNC)
1005 return;
1007 is_first_time_sync_configure_ = !HasSyncSetupCompleted();
1009 if (is_first_time_sync_configure_) {
1010 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success);
1011 } else {
1012 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success);
1015 base::Time on_backend_initialized_time = base::Time::Now();
1016 base::TimeDelta delta = on_backend_initialized_time -
1017 startup_controller_->start_backend_time();
1018 if (is_first_time_sync_configure_) {
1019 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeFirstTime", delta);
1020 } else {
1021 UMA_HISTOGRAM_LONG_TIMES("Sync.BackendInitializeRestoreTime", delta);
1025 void ProfileSyncService::PostBackendInitialization() {
1026 // Never get here for backup / restore.
1027 DCHECK_EQ(backend_mode_, SYNC);
1029 if (last_backup_time_) {
1030 DCHECK(device_info_sync_service_);
1031 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
1034 if (protocol_event_observers_.might_have_observers()) {
1035 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
1038 non_blocking_data_type_manager_.ConnectSyncBackend(
1039 backend_->GetSyncContextProxy());
1041 if (type_debug_info_observers_.might_have_observers()) {
1042 backend_->EnableDirectoryTypeDebugInfoForwarding();
1045 // If we have a cached passphrase use it to decrypt/encrypt data now that the
1046 // backend is initialized. We want to call this before notifying observers in
1047 // case this operation affects the "passphrase required" status.
1048 ConsumeCachedPassphraseIfPossible();
1050 // The very first time the backend initializes is effectively the first time
1051 // we can say we successfully "synced". LastSyncedTime will only be null in
1052 // this case, because the pref wasn't restored on StartUp.
1053 if (sync_prefs_.GetLastSyncedTime().is_null()) {
1054 UpdateLastSyncedTime();
1057 if (startup_controller_->auto_start_enabled() && !FirstSetupInProgress()) {
1058 // Backend is initialized but we're not in sync setup, so this must be an
1059 // autostart - mark our sync setup as completed and we'll start syncing
1060 // below.
1061 SetSyncSetupCompleted();
1064 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious
1065 // data type configuration because observer may flag setup as complete and
1066 // trigger data type configuration.
1067 if (HasSyncSetupCompleted()) {
1068 ConfigureDataTypeManager();
1069 } else {
1070 DCHECK(FirstSetupInProgress());
1073 NotifyObservers();
1076 void ProfileSyncService::OnBackendInitialized(
1077 const syncer::WeakHandle<syncer::JsBackend>& js_backend,
1078 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>&
1079 debug_info_listener,
1080 const std::string& cache_guid,
1081 bool success) {
1082 UpdateBackendInitUMA(success);
1084 if (!success) {
1085 // Something went unexpectedly wrong. Play it safe: stop syncing at once
1086 // and surface error UI to alert the user sync has stopped.
1087 // Keep the directory around for now so that on restart we will retry
1088 // again and potentially succeed in presence of transient file IO failures
1089 // or permissions issues, etc.
1091 // TODO(rlarocque): Consider making this UnrecoverableError less special.
1092 // Unlike every other UnrecoverableError, it does not delete our sync data.
1093 // This exception made sense at the time it was implemented, but our new
1094 // directory corruption recovery mechanism makes it obsolete. By the time
1095 // we get here, we will have already tried and failed to delete the
1096 // directory. It would be no big deal if we tried to delete it again.
1097 OnInternalUnrecoverableError(FROM_HERE,
1098 "BackendInitialize failure",
1099 false,
1100 ERROR_REASON_BACKEND_INIT_FAILURE);
1101 return;
1104 backend_initialized_ = true;
1106 sync_js_controller_.AttachJsBackend(js_backend);
1107 debug_info_listener_ = debug_info_listener;
1109 SigninClient* signin_client =
1110 ChromeSigninClientFactory::GetForProfile(profile_);
1111 DCHECK(signin_client);
1112 std::string signin_scoped_device_id =
1113 signin_client->GetSigninScopedDeviceId();
1115 // Initialize local device info.
1116 local_device_->Initialize(cache_guid, signin_scoped_device_id);
1118 DVLOG(1) << "Setting preferred types for non-blocking DTM";
1119 non_blocking_data_type_manager_.SetPreferredTypes(GetPreferredDataTypes());
1121 // Give the DataTypeControllers a handle to the now initialized backend
1122 // as a UserShare.
1123 for (DataTypeController::TypeMap::iterator it =
1124 directory_data_type_controllers_.begin();
1125 it != directory_data_type_controllers_.end(); ++it) {
1126 it->second->OnUserShareReady(GetUserShare());
1129 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK)
1130 ConfigureDataTypeManager();
1131 else
1132 PostBackendInitialization();
1135 void ProfileSyncService::OnSyncCycleCompleted() {
1136 UpdateLastSyncedTime();
1137 if (IsDataTypeControllerRunning(syncer::SESSIONS)) {
1138 // Trigger garbage collection of old sessions now that we've downloaded
1139 // any new session data.
1140 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind(
1141 &SessionsSyncManager::DoGarbageCollection,
1142 base::AsWeakPtr(sessions_sync_manager_.get())));
1144 DVLOG(2) << "Notifying observers sync cycle completed";
1145 NotifySyncCycleCompleted();
1148 void ProfileSyncService::OnExperimentsChanged(
1149 const syncer::Experiments& experiments) {
1150 if (current_experiments_.Matches(experiments))
1151 return;
1153 current_experiments_ = experiments;
1155 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel,
1156 experiments.gcm_invalidations_enabled);
1157 profile()->GetPrefs()->SetBoolean(
1158 autofill::prefs::kAutofillWalletSyncExperimentEnabled,
1159 experiments.wallet_sync_enabled);
1162 void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) {
1163 is_auth_in_progress_ = false;
1164 last_auth_error_ = error;
1166 NotifyObservers();
1169 namespace {
1171 AuthError ConnectionStatusToAuthError(
1172 syncer::ConnectionStatus status) {
1173 switch (status) {
1174 case syncer::CONNECTION_OK:
1175 return AuthError::AuthErrorNone();
1176 break;
1177 case syncer::CONNECTION_AUTH_ERROR:
1178 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS);
1179 break;
1180 case syncer::CONNECTION_SERVER_ERROR:
1181 return AuthError(AuthError::CONNECTION_FAILED);
1182 break;
1183 default:
1184 NOTREACHED();
1185 return AuthError(AuthError::CONNECTION_FAILED);
1189 } // namespace
1191 void ProfileSyncService::OnConnectionStatusChange(
1192 syncer::ConnectionStatus status) {
1193 connection_status_update_time_ = base::Time::Now();
1194 connection_status_ = status;
1195 if (status == syncer::CONNECTION_AUTH_ERROR) {
1196 // Sync server returned error indicating that access token is invalid. It
1197 // could be either expired or access is revoked. Let's request another
1198 // access token and if access is revoked then request for token will fail
1199 // with corresponding error. If access token is repeatedly reported
1200 // invalid, there may be some issues with server, e.g. authentication
1201 // state is inconsistent on sync and token server. In that case, we
1202 // backoff token requests exponentially to avoid hammering token server
1203 // too much and to avoid getting same token due to token server's caching
1204 // policy. |request_access_token_retry_timer_| is used to backoff request
1205 // triggered by both auth error and failure talking to GAIA server.
1206 // Therefore, we're likely to reach the backoff ceiling more quickly than
1207 // you would expect from looking at the BackoffPolicy if both types of
1208 // errors happen. We shouldn't receive two errors back-to-back without
1209 // attempting a token/sync request in between, thus crank up request delay
1210 // unnecessary. This is because we won't make a sync request if we hit an
1211 // error until GAIA succeeds at sending a new token, and we won't request
1212 // a new token unless sync reports a token failure. But to be safe, don't
1213 // schedule request if this happens.
1214 if (request_access_token_retry_timer_.IsRunning()) {
1215 // The timer to perform a request later is already running; nothing
1216 // further needs to be done at this point.
1217 } else if (request_access_token_backoff_.failure_count() == 0) {
1218 // First time request without delay. Currently invalid token is used
1219 // to initialize sync backend and we'll always end up here. We don't
1220 // want to delay initialization.
1221 request_access_token_backoff_.InformOfRequest(false);
1222 RequestAccessToken();
1223 } else {
1224 request_access_token_backoff_.InformOfRequest(false);
1225 request_access_token_retry_timer_.Start(
1226 FROM_HERE,
1227 request_access_token_backoff_.GetTimeUntilRelease(),
1228 base::Bind(&ProfileSyncService::RequestAccessToken,
1229 weak_factory_.GetWeakPtr()));
1231 } else {
1232 // Reset backoff time after successful connection.
1233 if (status == syncer::CONNECTION_OK) {
1234 // Request shouldn't be scheduled at this time. But if it is, it's
1235 // possible that sync flips between OK and auth error states rapidly,
1236 // thus hammers token server. To be safe, only reset backoff delay when
1237 // no scheduled request.
1238 if (request_access_token_retry_timer_.IsRunning()) {
1239 NOTREACHED();
1240 } else {
1241 request_access_token_backoff_.Reset();
1245 const GoogleServiceAuthError auth_error =
1246 ConnectionStatusToAuthError(status);
1247 DVLOG(1) << "Connection status change: " << auth_error.ToString();
1248 UpdateAuthErrorState(auth_error);
1252 void ProfileSyncService::StopSyncingPermanently() {
1253 sync_prefs_.SetStartSuppressed(true);
1254 DisableForUser();
1257 void ProfileSyncService::OnPassphraseRequired(
1258 syncer::PassphraseRequiredReason reason,
1259 const sync_pb::EncryptedData& pending_keys) {
1260 DCHECK(backend_.get());
1261 DCHECK(backend_->IsNigoriEnabled());
1263 // TODO(lipalani) : add this check to other locations as well.
1264 if (HasUnrecoverableError()) {
1265 // When unrecoverable error is detected we post a task to shutdown the
1266 // backend. The task might not have executed yet.
1267 return;
1270 DVLOG(1) << "Passphrase required with reason: "
1271 << syncer::PassphraseRequiredReasonToString(reason);
1272 passphrase_required_reason_ = reason;
1274 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1275 if (directory_data_type_manager_) {
1276 // Reconfigure without the encrypted types (excluded implicitly via the
1277 // failed datatypes handler).
1278 directory_data_type_manager_->Configure(types,
1279 syncer::CONFIGURE_REASON_CRYPTO);
1282 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1284 // Notify observers that the passphrase status may have changed.
1285 NotifyObservers();
1288 void ProfileSyncService::OnPassphraseAccepted() {
1289 DVLOG(1) << "Received OnPassphraseAccepted.";
1291 // If the pending keys were resolved via keystore, it's possible we never
1292 // consumed our cached passphrase. Clear it now.
1293 if (!cached_passphrase_.empty())
1294 cached_passphrase_.clear();
1296 // Reset passphrase_required_reason_ since we know we no longer require the
1297 // passphrase. We do this here rather than down in ResolvePassphraseRequired()
1298 // because that can be called by OnPassphraseRequired() if no encrypted data
1299 // types are enabled, and we don't want to clobber the true passphrase error.
1300 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1302 // Make sure the data types that depend on the passphrase are started at
1303 // this time.
1304 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes();
1305 if (directory_data_type_manager_) {
1306 // Re-enable any encrypted types if necessary.
1307 directory_data_type_manager_->Configure(types,
1308 syncer::CONFIGURE_REASON_CRYPTO);
1311 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005.
1313 NotifyObservers();
1316 void ProfileSyncService::OnEncryptedTypesChanged(
1317 syncer::ModelTypeSet encrypted_types,
1318 bool encrypt_everything) {
1319 encrypted_types_ = encrypted_types;
1320 encrypt_everything_ = encrypt_everything;
1321 DCHECK(encrypt_everything_allowed_ || !encrypt_everything_);
1322 DVLOG(1) << "Encrypted types changed to "
1323 << syncer::ModelTypeSetToString(encrypted_types_)
1324 << " (encrypt everything is set to "
1325 << (encrypt_everything_ ? "true" : "false") << ")";
1326 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
1328 NotifyObservers();
1331 void ProfileSyncService::OnEncryptionComplete() {
1332 DVLOG(1) << "Encryption complete";
1333 if (encryption_pending_ && encrypt_everything_) {
1334 encryption_pending_ = false;
1335 // This is to nudge the integration tests when encryption is
1336 // finished.
1337 NotifyObservers();
1341 void ProfileSyncService::OnMigrationNeededForTypes(
1342 syncer::ModelTypeSet types) {
1343 DCHECK(backend_initialized_);
1344 DCHECK(directory_data_type_manager_.get());
1346 // Migrator must be valid, because we don't sync until it is created and this
1347 // callback originates from a sync cycle.
1348 migrator_->MigrateTypes(types);
1351 void ProfileSyncService::OnActionableError(const SyncProtocolError& error) {
1352 last_actionable_error_ = error;
1353 DCHECK_NE(last_actionable_error_.action,
1354 syncer::UNKNOWN_ACTION);
1355 switch (error.action) {
1356 case syncer::UPGRADE_CLIENT:
1357 case syncer::CLEAR_USER_DATA_AND_RESYNC:
1358 case syncer::ENABLE_SYNC_ON_ACCOUNT:
1359 case syncer::STOP_AND_RESTART_SYNC:
1360 // TODO(lipalani) : if setup in progress we want to display these
1361 // actions in the popup. The current experience might not be optimal for
1362 // the user. We just dismiss the dialog.
1363 if (startup_controller_->setup_in_progress()) {
1364 StopSyncingPermanently();
1365 expect_sync_configuration_aborted_ = true;
1367 // Trigger an unrecoverable error to stop syncing.
1368 OnInternalUnrecoverableError(FROM_HERE,
1369 last_actionable_error_.error_description,
1370 true,
1371 ERROR_REASON_ACTIONABLE_ERROR);
1372 break;
1373 case syncer::DISABLE_SYNC_AND_ROLLBACK:
1374 backup_rollback_controller_->OnRollbackReceived();
1375 // Fall through to shutdown backend and sign user out.
1376 case syncer::DISABLE_SYNC_ON_CLIENT:
1377 StopSyncingPermanently();
1378 #if !defined(OS_CHROMEOS)
1379 // On desktop Chrome, sign out the user after a dashboard clear.
1380 // Skip sign out on ChromeOS/Android.
1381 if (!startup_controller_->auto_start_enabled()) {
1382 SigninManagerFactory::GetForProfile(profile_)->SignOut(
1383 signin_metrics::SERVER_FORCED_DISABLE);
1385 #endif
1386 break;
1387 case syncer::ROLLBACK_DONE:
1388 backup_rollback_controller_->OnRollbackDone();
1389 break;
1390 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT:
1391 // Sync disabled by domain admin. we should stop syncing until next
1392 // restart.
1393 sync_disabled_by_admin_ = true;
1394 ShutdownImpl(syncer::DISABLE_SYNC);
1395 break;
1396 default:
1397 NOTREACHED();
1399 NotifyObservers();
1401 if (error.action == syncer::DISABLE_SYNC_ON_CLIENT ||
1402 (error.action == syncer::DISABLE_SYNC_AND_ROLLBACK &&
1403 !backup_rollback_controller_->StartRollback())) {
1404 // Clean up backup data for sign-out only or when rollback is disabled.
1405 CleanUpBackup();
1406 } else if (error.action == syncer::ROLLBACK_DONE) {
1407 // Shut down ROLLBACK backend and delete backup DB.
1408 ShutdownImpl(syncer::DISABLE_SYNC);
1409 sync_prefs_.ClearFirstSyncTime();
1413 void ProfileSyncService::OnConfigureDone(
1414 const DataTypeManager::ConfigureResult& result) {
1415 configure_status_ = result.status;
1416 data_type_status_table_ = result.data_type_status_table;
1418 if (backend_mode_ != SYNC) {
1419 if (configure_status_ == DataTypeManager::OK) {
1420 StartSyncingWithServer();
1422 // Backup is done after models are associated.
1423 if (backend_mode_ == BACKUP)
1424 backup_finished_ = true;
1426 // Asynchronously check whether sync needs to start.
1427 base::MessageLoop::current()->PostTask(
1428 FROM_HERE, base::Bind(&ProfileSyncService::TryStartSyncAfterBackup,
1429 startup_controller_weak_factory_.GetWeakPtr()));
1430 } else if (!expect_sync_configuration_aborted_) {
1431 DVLOG(1) << "Backup/rollback backend failed to configure.";
1432 ShutdownImpl(syncer::STOP_SYNC);
1435 return;
1438 // We should have cleared our cached passphrase before we get here (in
1439 // OnBackendInitialized()).
1440 DCHECK(cached_passphrase_.empty());
1442 if (!sync_configure_start_time_.is_null()) {
1443 if (result.status == DataTypeManager::OK) {
1444 base::Time sync_configure_stop_time = base::Time::Now();
1445 base::TimeDelta delta = sync_configure_stop_time -
1446 sync_configure_start_time_;
1447 if (is_first_time_sync_configure_) {
1448 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta);
1449 } else {
1450 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime",
1451 delta);
1454 sync_configure_start_time_ = base::Time();
1457 // Notify listeners that configuration is done.
1458 content::NotificationService::current()->Notify(
1459 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE,
1460 content::Source<ProfileSyncService>(this),
1461 content::NotificationService::NoDetails());
1463 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_;
1464 // The possible status values:
1465 // ABORT - Configuration was aborted. This is not an error, if
1466 // initiated by user.
1467 // OK - Some or all types succeeded.
1468 // Everything else is an UnrecoverableError. So treat it as such.
1470 // First handle the abort case.
1471 if (configure_status_ == DataTypeManager::ABORTED &&
1472 expect_sync_configuration_aborted_) {
1473 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted";
1474 expect_sync_configuration_aborted_ = false;
1475 return;
1478 // Handle unrecoverable error.
1479 if (configure_status_ != DataTypeManager::OK) {
1480 // Something catastrophic had happened. We should only have one
1481 // error representing it.
1482 syncer::SyncError error =
1483 data_type_status_table_.GetUnrecoverableError();
1484 DCHECK(error.IsSet());
1485 std::string message =
1486 "Sync configuration failed with status " +
1487 DataTypeManager::ConfigureStatusToString(configure_status_) +
1488 " caused by " +
1489 syncer::ModelTypeSetToString(
1490 data_type_status_table_.GetUnrecoverableErrorTypes()) +
1491 ": " + error.message();
1492 LOG(ERROR) << "ProfileSyncService error: " << message;
1493 OnInternalUnrecoverableError(error.location(),
1494 message,
1495 true,
1496 ERROR_REASON_CONFIGURATION_FAILURE);
1497 return;
1500 // We should never get in a state where we have no encrypted datatypes
1501 // enabled, and yet we still think we require a passphrase for decryption.
1502 DCHECK(!(IsPassphraseRequiredForDecryption() &&
1503 !IsEncryptedDatatypeEnabled()));
1505 // This must be done before we start syncing with the server to avoid
1506 // sending unencrypted data up on a first time sync.
1507 if (encryption_pending_)
1508 backend_->EnableEncryptEverything();
1509 NotifyObservers();
1511 if (migrator_.get() &&
1512 migrator_->state() != browser_sync::BackendMigrator::IDLE) {
1513 // Migration in progress. Let the migrator know we just finished
1514 // configuring something. It will be up to the migrator to call
1515 // StartSyncingWithServer() if migration is now finished.
1516 migrator_->OnConfigureDone(result);
1517 } else {
1518 StartSyncingWithServer();
1522 void ProfileSyncService::OnConfigureStart() {
1523 sync_configure_start_time_ = base::Time::Now();
1524 NotifyObservers();
1527 ProfileSyncService::SyncStatusSummary
1528 ProfileSyncService::QuerySyncStatusSummary() {
1529 if (HasUnrecoverableError()) {
1530 return UNRECOVERABLE_ERROR;
1531 } else if (!backend_) {
1532 return NOT_ENABLED;
1533 } else if (backend_mode_ == BACKUP) {
1534 return BACKUP_USER_DATA;
1535 } else if (backend_mode_ == ROLLBACK) {
1536 return ROLLBACK_USER_DATA;
1537 } else if (backend_.get() && !HasSyncSetupCompleted()) {
1538 return SETUP_INCOMPLETE;
1539 } else if (
1540 backend_.get() && HasSyncSetupCompleted() &&
1541 directory_data_type_manager_.get() &&
1542 directory_data_type_manager_->state() == DataTypeManager::STOPPED) {
1543 return DATATYPES_NOT_INITIALIZED;
1544 } else if (SyncActive()) {
1545 return INITIALIZED;
1547 return UNKNOWN_ERROR;
1550 std::string ProfileSyncService::QuerySyncStatusSummaryString() {
1551 SyncStatusSummary status = QuerySyncStatusSummary();
1553 std::string config_status_str =
1554 configure_status_ != DataTypeManager::UNKNOWN ?
1555 DataTypeManager::ConfigureStatusToString(configure_status_) : "";
1557 switch (status) {
1558 case UNRECOVERABLE_ERROR:
1559 return "Unrecoverable error detected";
1560 case NOT_ENABLED:
1561 return "Syncing not enabled";
1562 case SETUP_INCOMPLETE:
1563 return "First time sync setup incomplete";
1564 case DATATYPES_NOT_INITIALIZED:
1565 return "Datatypes not fully initialized";
1566 case INITIALIZED:
1567 return "Sync service initialized";
1568 case BACKUP_USER_DATA:
1569 return "Backing-up user data. Status: " + config_status_str;
1570 case ROLLBACK_USER_DATA:
1571 return "Restoring user data. Status: " + config_status_str;
1572 default:
1573 return "Status unknown: Internal error?";
1577 std::string ProfileSyncService::GetBackendInitializationStateString() const {
1578 return startup_controller_->GetBackendInitializationStateString();
1581 bool ProfileSyncService::auto_start_enabled() const {
1582 return startup_controller_->auto_start_enabled();
1585 bool ProfileSyncService::setup_in_progress() const {
1586 return startup_controller_->setup_in_progress();
1589 bool ProfileSyncService::QueryDetailedSyncStatus(
1590 SyncBackendHost::Status* result) {
1591 if (backend_.get() && backend_initialized_) {
1592 *result = backend_->GetDetailedStatus();
1593 return true;
1594 } else {
1595 SyncBackendHost::Status status;
1596 status.sync_protocol_error = last_actionable_error_;
1597 *result = status;
1598 return false;
1602 const AuthError& ProfileSyncService::GetAuthError() const {
1603 return last_auth_error_;
1606 bool ProfileSyncService::FirstSetupInProgress() const {
1607 return !HasSyncSetupCompleted() && startup_controller_->setup_in_progress();
1610 void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) {
1611 // This method is a no-op if |setup_in_progress_| remains unchanged.
1612 if (startup_controller_->setup_in_progress() == setup_in_progress)
1613 return;
1615 startup_controller_->set_setup_in_progress(setup_in_progress);
1616 if (!setup_in_progress && backend_initialized())
1617 ReconfigureDatatypeManager();
1618 NotifyObservers();
1621 bool ProfileSyncService::SyncActive() const {
1622 return backend_initialized_ && backend_mode_ == SYNC &&
1623 directory_data_type_manager_ &&
1624 directory_data_type_manager_->state() != DataTypeManager::STOPPED;
1627 bool ProfileSyncService::backend_initialized() const {
1628 return backend_initialized_;
1631 ProfileSyncService::BackendMode ProfileSyncService::backend_mode() const {
1632 return backend_mode_;
1635 bool ProfileSyncService::ConfigurationDone() const {
1636 return directory_data_type_manager_ &&
1637 directory_data_type_manager_->state() == DataTypeManager::CONFIGURED;
1640 bool ProfileSyncService::waiting_for_auth() const {
1641 return is_auth_in_progress_;
1644 const syncer::Experiments& ProfileSyncService::current_experiments() const {
1645 return current_experiments_;
1648 bool ProfileSyncService::HasUnrecoverableError() const {
1649 return unrecoverable_error_reason_ != ERROR_REASON_UNSET;
1652 bool ProfileSyncService::IsPassphraseRequired() const {
1653 return passphrase_required_reason_ !=
1654 syncer::REASON_PASSPHRASE_NOT_REQUIRED;
1657 bool ProfileSyncService::IsPassphraseRequiredForDecryption() const {
1658 // If there is an encrypted datatype enabled and we don't have the proper
1659 // passphrase, we must prompt the user for a passphrase. The only way for the
1660 // user to avoid entering their passphrase is to disable the encrypted types.
1661 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired();
1664 base::string16 ProfileSyncService::GetLastSyncedTimeString() const {
1665 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
1666 if (last_synced_time.is_null())
1667 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER);
1669 base::TimeDelta time_since_last_sync = base::Time::Now() - last_synced_time;
1671 if (time_since_last_sync < base::TimeDelta::FromMinutes(1))
1672 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW);
1674 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED,
1675 ui::TimeFormat::LENGTH_SHORT,
1676 time_since_last_sync);
1679 void ProfileSyncService::UpdateSelectedTypesHistogram(
1680 bool sync_everything, const syncer::ModelTypeSet chosen_types) const {
1681 if (!HasSyncSetupCompleted() ||
1682 sync_everything != sync_prefs_.HasKeepEverythingSynced()) {
1683 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything);
1686 // Only log the data types that are shown in the sync settings ui.
1687 // Note: the order of these types must match the ordering of
1688 // the respective types in ModelType
1689 const sync_driver::user_selectable_type::UserSelectableSyncType
1690 user_selectable_types[] = {
1691 sync_driver::user_selectable_type::BOOKMARKS,
1692 sync_driver::user_selectable_type::PREFERENCES,
1693 sync_driver::user_selectable_type::PASSWORDS,
1694 sync_driver::user_selectable_type::AUTOFILL,
1695 sync_driver::user_selectable_type::THEMES,
1696 sync_driver::user_selectable_type::TYPED_URLS,
1697 sync_driver::user_selectable_type::EXTENSIONS,
1698 sync_driver::user_selectable_type::APPS,
1699 sync_driver::user_selectable_type::WIFI_CREDENTIAL,
1700 sync_driver::user_selectable_type::PROXY_TABS,
1703 static_assert(35 == syncer::MODEL_TYPE_COUNT,
1704 "custom config histogram must be updated");
1706 if (!sync_everything) {
1707 const syncer::ModelTypeSet current_types = GetPreferredDataTypes();
1709 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes();
1710 syncer::ModelTypeSet::Iterator it = type_set.First();
1712 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size());
1714 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good();
1715 ++i, it.Inc()) {
1716 const syncer::ModelType type = it.Get();
1717 if (chosen_types.Has(type) &&
1718 (!HasSyncSetupCompleted() || !current_types.Has(type))) {
1719 // Selected type has changed - log it.
1720 UMA_HISTOGRAM_ENUMERATION(
1721 "Sync.CustomSync",
1722 user_selectable_types[i],
1723 sync_driver::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1);
1729 #if defined(OS_CHROMEOS)
1730 void ProfileSyncService::RefreshSpareBootstrapToken(
1731 const std::string& passphrase) {
1732 sync_driver::SystemEncryptor encryptor;
1733 syncer::Cryptographer temp_cryptographer(&encryptor);
1734 // The first 2 params (hostname and username) doesn't have any effect here.
1735 syncer::KeyParams key_params = {"localhost", "dummy", passphrase};
1737 std::string bootstrap_token;
1738 if (!temp_cryptographer.AddKey(key_params)) {
1739 NOTREACHED() << "Failed to add key to cryptographer.";
1741 temp_cryptographer.GetBootstrapToken(&bootstrap_token);
1742 sync_prefs_.SetSpareBootstrapToken(bootstrap_token);
1744 #endif
1746 void ProfileSyncService::OnUserChoseDatatypes(
1747 bool sync_everything,
1748 syncer::ModelTypeSet chosen_types) {
1749 if (!backend_.get() && !HasUnrecoverableError()) {
1750 NOTREACHED();
1751 return;
1754 UpdateSelectedTypesHistogram(sync_everything, chosen_types);
1755 sync_prefs_.SetKeepEverythingSynced(sync_everything);
1757 if (directory_data_type_manager_.get())
1758 directory_data_type_manager_->ResetDataTypeErrors();
1759 ChangePreferredDataTypes(chosen_types);
1762 void ProfileSyncService::ChangePreferredDataTypes(
1763 syncer::ModelTypeSet preferred_types) {
1765 DVLOG(1) << "ChangePreferredDataTypes invoked";
1766 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1767 const syncer::ModelTypeSet registered_preferred_types =
1768 Intersection(registered_types, preferred_types);
1769 sync_prefs_.SetPreferredDataTypes(registered_types,
1770 registered_preferred_types);
1772 // Now reconfigure the DTM.
1773 ReconfigureDatatypeManager();
1775 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked
1776 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell
1777 // which types should be enabled and when.
1780 syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const {
1781 if (!SyncActive() || !ConfigurationDone())
1782 return syncer::ModelTypeSet();
1783 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes();
1784 const syncer::ModelTypeSet failed_types =
1785 data_type_status_table_.GetFailedTypes();
1786 return Difference(preferred_types, failed_types);
1789 syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const {
1790 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes();
1791 const syncer::ModelTypeSet preferred_types =
1792 sync_prefs_.GetPreferredDataTypes(registered_types);
1793 const syncer::ModelTypeSet enforced_types =
1794 Intersection(GetDataTypesFromPreferenceProviders(), registered_types);
1795 return Union(preferred_types, enforced_types);
1798 syncer::ModelTypeSet
1799 ProfileSyncService::GetPreferredDirectoryDataTypes() const {
1800 const syncer::ModelTypeSet registered_directory_types =
1801 GetRegisteredDirectoryDataTypes();
1802 const syncer::ModelTypeSet preferred_types =
1803 sync_prefs_.GetPreferredDataTypes(registered_directory_types);
1804 const syncer::ModelTypeSet enforced_types =
1805 Intersection(GetDataTypesFromPreferenceProviders(),
1806 registered_directory_types);
1807 return Union(preferred_types, enforced_types);
1810 syncer::ModelTypeSet
1811 ProfileSyncService::GetPreferredNonBlockingDataTypes() const {
1812 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes());
1815 syncer::ModelTypeSet ProfileSyncService::GetForcedDataTypes() const {
1816 // TODO(treib,zea): When SyncPrefs also implements SyncTypePreferenceProvider,
1817 // we'll need another way to distinguish user-choosable types from
1818 // programmatically-enabled types.
1819 return GetDataTypesFromPreferenceProviders();
1822 syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const {
1823 return Union(GetRegisteredDirectoryDataTypes(),
1824 GetRegisteredNonBlockingDataTypes());
1827 syncer::ModelTypeSet
1828 ProfileSyncService::GetRegisteredDirectoryDataTypes() const {
1829 syncer::ModelTypeSet registered_types;
1830 // The directory_data_type_controllers_ are determined by command-line flags;
1831 // that's effectively what controls the values returned here.
1832 for (DataTypeController::TypeMap::const_iterator it =
1833 directory_data_type_controllers_.begin();
1834 it != directory_data_type_controllers_.end(); ++it) {
1835 registered_types.Put(it->first);
1837 return registered_types;
1840 syncer::ModelTypeSet
1841 ProfileSyncService::GetRegisteredNonBlockingDataTypes() const {
1842 return non_blocking_data_type_manager_.GetRegisteredTypes();
1845 bool ProfileSyncService::IsUsingSecondaryPassphrase() const {
1846 syncer::PassphraseType passphrase_type = GetPassphraseType();
1847 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE ||
1848 passphrase_type == syncer::CUSTOM_PASSPHRASE;
1851 syncer::PassphraseType ProfileSyncService::GetPassphraseType() const {
1852 return backend_->GetPassphraseType();
1855 base::Time ProfileSyncService::GetExplicitPassphraseTime() const {
1856 return backend_->GetExplicitPassphraseTime();
1859 bool ProfileSyncService::IsCryptographerReady(
1860 const syncer::BaseTransaction* trans) const {
1861 return backend_.get() && backend_->IsCryptographerReady(trans);
1864 void ProfileSyncService::ConfigurePriorityDataTypes() {
1865 const syncer::ModelTypeSet priority_types =
1866 Intersection(GetPreferredDirectoryDataTypes(),
1867 syncer::PriorityUserTypes());
1868 if (!priority_types.Empty()) {
1869 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ?
1870 syncer::CONFIGURE_REASON_RECONFIGURATION :
1871 syncer::CONFIGURE_REASON_NEW_CLIENT;
1872 directory_data_type_manager_->Configure(priority_types, reason);
1876 void ProfileSyncService::ConfigureDataTypeManager() {
1877 // Don't configure datatypes if the setup UI is still on the screen - this
1878 // is to help multi-screen setting UIs (like iOS) where they don't want to
1879 // start syncing data until the user is done configuring encryption options,
1880 // etc. ReconfigureDatatypeManager() will get called again once the UI calls
1881 // SetSetupInProgress(false).
1882 if (backend_mode_ == SYNC && startup_controller_->setup_in_progress())
1883 return;
1885 bool restart = false;
1886 if (!directory_data_type_manager_) {
1887 restart = true;
1888 directory_data_type_manager_.reset(
1889 factory_->CreateDataTypeManager(debug_info_listener_,
1890 &directory_data_type_controllers_,
1891 this,
1892 backend_.get(),
1893 this));
1895 // We create the migrator at the same time.
1896 migrator_.reset(
1897 new browser_sync::BackendMigrator(
1898 profile_->GetDebugName(), GetUserShare(),
1899 this, directory_data_type_manager_.get(),
1900 base::Bind(&ProfileSyncService::StartSyncingWithServer,
1901 base::Unretained(this))));
1904 syncer::ModelTypeSet types;
1905 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN;
1906 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) {
1907 types = syncer::BackupTypes();
1908 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK;
1909 } else {
1910 types = GetPreferredDirectoryDataTypes();
1911 if (!HasSyncSetupCompleted()) {
1912 reason = syncer::CONFIGURE_REASON_NEW_CLIENT;
1913 } else if (restart) {
1914 // Datatype downloads on restart are generally due to newly supported
1915 // datatypes (although it's also possible we're picking up where a failed
1916 // previous configuration left off).
1917 // TODO(sync): consider detecting configuration recovery and setting
1918 // the reason here appropriately.
1919 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE;
1920 } else {
1921 // The user initiated a reconfiguration (either to add or remove types).
1922 reason = syncer::CONFIGURE_REASON_RECONFIGURATION;
1926 directory_data_type_manager_->Configure(types, reason);
1929 syncer::UserShare* ProfileSyncService::GetUserShare() const {
1930 if (backend_.get() && backend_initialized_) {
1931 return backend_->GetUserShare();
1933 NOTREACHED();
1934 return NULL;
1937 syncer::sessions::SyncSessionSnapshot
1938 ProfileSyncService::GetLastSessionSnapshot() const {
1939 if (backend_)
1940 return backend_->GetLastSessionSnapshot();
1941 return syncer::sessions::SyncSessionSnapshot();
1944 bool ProfileSyncService::HasUnsyncedItems() const {
1945 if (HasSyncingBackend() && backend_initialized_) {
1946 return backend_->HasUnsyncedItems();
1948 NOTREACHED();
1949 return false;
1952 browser_sync::BackendMigrator*
1953 ProfileSyncService::GetBackendMigratorForTest() {
1954 return migrator_.get();
1957 void ProfileSyncService::GetModelSafeRoutingInfo(
1958 syncer::ModelSafeRoutingInfo* out) const {
1959 if (backend_.get() && backend_initialized_) {
1960 backend_->GetModelSafeRoutingInfo(out);
1961 } else {
1962 NOTREACHED();
1966 base::Value* ProfileSyncService::GetTypeStatusMap() const {
1967 scoped_ptr<base::ListValue> result(new base::ListValue());
1969 if (!backend_.get() || !backend_initialized_) {
1970 return result.release();
1973 DataTypeStatusTable::TypeErrorMap error_map =
1974 data_type_status_table_.GetAllErrors();
1975 ModelTypeSet active_types;
1976 ModelTypeSet passive_types;
1977 ModelSafeRoutingInfo routing_info;
1978 backend_->GetModelSafeRoutingInfo(&routing_info);
1979 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin();
1980 it != routing_info.end(); ++it) {
1981 if (it->second == syncer::GROUP_PASSIVE) {
1982 passive_types.Put(it->first);
1983 } else {
1984 active_types.Put(it->first);
1988 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus();
1989 ModelTypeSet &throttled_types(detailed_status.throttled_types);
1990 ModelTypeSet registered = GetRegisteredDataTypes();
1991 scoped_ptr<base::DictionaryValue> type_status_header(
1992 new base::DictionaryValue());
1994 type_status_header->SetString("name", "Model Type");
1995 type_status_header->SetString("status", "header");
1996 type_status_header->SetString("value", "Group Type");
1997 type_status_header->SetString("num_entries", "Total Entries");
1998 type_status_header->SetString("num_live", "Live Entries");
1999 result->Append(type_status_header.release());
2001 scoped_ptr<base::DictionaryValue> type_status;
2002 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) {
2003 ModelType type = it.Get();
2005 type_status.reset(new base::DictionaryValue());
2006 type_status->SetString("name", ModelTypeToString(type));
2008 if (error_map.find(type) != error_map.end()) {
2009 const syncer::SyncError &error = error_map.find(type)->second;
2010 DCHECK(error.IsSet());
2011 switch (error.GetSeverity()) {
2012 case syncer::SyncError::SYNC_ERROR_SEVERITY_ERROR: {
2013 std::string error_text = "Error: " + error.location().ToString() +
2014 ", " + error.GetMessagePrefix() + error.message();
2015 type_status->SetString("status", "error");
2016 type_status->SetString("value", error_text);
2018 break;
2019 case syncer::SyncError::SYNC_ERROR_SEVERITY_INFO:
2020 type_status->SetString("status", "disabled");
2021 type_status->SetString("value", error.message());
2022 break;
2023 default:
2024 NOTREACHED() << "Unexpected error severity.";
2025 break;
2027 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) {
2028 // Show a proxy type in "ok" state unless it is disabled by user.
2029 DCHECK(!throttled_types.Has(type));
2030 type_status->SetString("status", "ok");
2031 type_status->SetString("value", "Passive");
2032 } else if (throttled_types.Has(type) && passive_types.Has(type)) {
2033 type_status->SetString("status", "warning");
2034 type_status->SetString("value", "Passive, Throttled");
2035 } else if (passive_types.Has(type)) {
2036 type_status->SetString("status", "warning");
2037 type_status->SetString("value", "Passive");
2038 } else if (throttled_types.Has(type)) {
2039 type_status->SetString("status", "warning");
2040 type_status->SetString("value", "Throttled");
2041 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) {
2042 type_status->SetString("status", "ok");
2043 type_status->SetString("value", "Non-Blocking");
2044 } else if (active_types.Has(type)) {
2045 type_status->SetString("status", "ok");
2046 type_status->SetString("value", "Active: " +
2047 ModelSafeGroupToString(routing_info[type]));
2048 } else {
2049 type_status->SetString("status", "warning");
2050 type_status->SetString("value", "Disabled by User");
2053 int live_count = detailed_status.num_entries_by_type[type] -
2054 detailed_status.num_to_delete_entries_by_type[type];
2055 type_status->SetInteger("num_entries",
2056 detailed_status.num_entries_by_type[type]);
2057 type_status->SetInteger("num_live", live_count);
2059 result->Append(type_status.release());
2061 return result.release();
2064 void ProfileSyncService::DeactivateDataType(syncer::ModelType type) {
2065 if (!backend_)
2066 return;
2067 backend_->DeactivateDataType(type);
2070 void ProfileSyncService::ConsumeCachedPassphraseIfPossible() {
2071 // If no cached passphrase, or sync backend hasn't started up yet, just exit.
2072 // If the backend isn't running yet, OnBackendInitialized() will call this
2073 // method again after the backend starts up.
2074 if (cached_passphrase_.empty() || !backend_initialized())
2075 return;
2077 // Backend is up and running, so we can consume the cached passphrase.
2078 std::string passphrase = cached_passphrase_;
2079 cached_passphrase_.clear();
2081 // If we need a passphrase to decrypt data, try the cached passphrase.
2082 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) {
2083 if (SetDecryptionPassphrase(passphrase)) {
2084 DVLOG(1) << "Cached passphrase successfully decrypted pending keys";
2085 return;
2089 // If we get here, we don't have pending keys (or at least, the passphrase
2090 // doesn't decrypt them) - just try to re-encrypt using the encryption
2091 // passphrase.
2092 if (!IsUsingSecondaryPassphrase())
2093 SetEncryptionPassphrase(passphrase, IMPLICIT);
2096 void ProfileSyncService::RequestAccessToken() {
2097 // Only one active request at a time.
2098 if (access_token_request_ != NULL)
2099 return;
2100 request_access_token_retry_timer_.Stop();
2101 OAuth2TokenService::ScopeSet oauth2_scopes;
2102 oauth2_scopes.insert(signin_->GetSyncScopeToUse());
2104 // Invalidate previous token, otherwise token service will return the same
2105 // token again.
2106 const std::string& account_id = signin_->GetAccountIdToUse();
2107 if (!access_token_.empty()) {
2108 oauth2_token_service_->InvalidateToken(
2109 account_id, oauth2_scopes, access_token_);
2112 access_token_.clear();
2114 token_request_time_ = base::Time::Now();
2115 token_receive_time_ = base::Time();
2116 next_token_request_time_ = base::Time();
2117 access_token_request_ =
2118 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this);
2121 void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase,
2122 PassphraseType type) {
2123 // This should only be called when the backend has been initialized.
2124 DCHECK(backend_initialized());
2125 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) <<
2126 "Data is already encrypted using an explicit passphrase";
2127 DCHECK(!(type == EXPLICIT &&
2128 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) <<
2129 "Can not set explicit passphrase when decryption is needed.";
2131 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit")
2132 << " passphrase for encryption.";
2133 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) {
2134 // REASON_ENCRYPTION implies that the cryptographer does not have pending
2135 // keys. Hence, as long as we're not trying to do an invalid passphrase
2136 // change (e.g. explicit -> explicit or explicit -> implicit), we know this
2137 // will succeed. If for some reason a new encryption key arrives via
2138 // sync later, the SBH will trigger another OnPassphraseRequired().
2139 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED;
2140 NotifyObservers();
2142 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT);
2145 bool ProfileSyncService::SetDecryptionPassphrase(
2146 const std::string& passphrase) {
2147 if (IsPassphraseRequired()) {
2148 DVLOG(1) << "Setting passphrase for decryption.";
2149 return backend_->SetDecryptionPassphrase(passphrase);
2150 } else {
2151 NOTREACHED() << "SetDecryptionPassphrase must not be called when "
2152 "IsPassphraseRequired() is false.";
2153 return false;
2157 bool ProfileSyncService::EncryptEverythingAllowed() const {
2158 return encrypt_everything_allowed_;
2161 void ProfileSyncService::SetEncryptEverythingAllowed(bool allowed) {
2162 DCHECK(allowed || !backend_initialized() || !EncryptEverythingEnabled());
2163 encrypt_everything_allowed_ = allowed;
2166 void ProfileSyncService::EnableEncryptEverything() {
2167 DCHECK(EncryptEverythingAllowed());
2169 // Tests override backend_initialized() to always return true, so we
2170 // must check that instead of |backend_initialized_|.
2171 // TODO(akalin): Fix the above. :/
2172 DCHECK(backend_initialized());
2173 // TODO(atwilson): Persist the encryption_pending_ flag to address the various
2174 // problems around cancelling encryption in the background (crbug.com/119649).
2175 if (!encrypt_everything_)
2176 encryption_pending_ = true;
2179 bool ProfileSyncService::encryption_pending() const {
2180 // We may be called during the setup process before we're
2181 // initialized (via IsEncryptedDatatypeEnabled and
2182 // IsPassphraseRequiredForDecryption).
2183 return encryption_pending_;
2186 bool ProfileSyncService::EncryptEverythingEnabled() const {
2187 DCHECK(backend_initialized_);
2188 return encrypt_everything_ || encryption_pending_;
2191 syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const {
2192 DCHECK(encrypted_types_.Has(syncer::PASSWORDS));
2193 // We may be called during the setup process before we're
2194 // initialized. In this case, we default to the sensitive types.
2195 return encrypted_types_;
2198 void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) {
2199 if (is_sync_managed) {
2200 DisableForUser();
2201 } else {
2202 // Sync is no longer disabled by policy. Try starting it up if appropriate.
2203 startup_controller_->TryStart();
2207 void ProfileSyncService::GoogleSigninSucceeded(const std::string& account_id,
2208 const std::string& username,
2209 const std::string& password) {
2210 if (!sync_prefs_.IsStartSuppressed() && !password.empty()) {
2211 cached_passphrase_ = password;
2212 // Try to consume the passphrase we just cached. If the sync backend
2213 // is not running yet, the passphrase will remain cached until the
2214 // backend starts up.
2215 ConsumeCachedPassphraseIfPossible();
2217 #if defined(OS_CHROMEOS)
2218 RefreshSpareBootstrapToken(password);
2219 #endif
2220 if (!backend_initialized() || GetAuthError().state() != AuthError::NONE) {
2221 // Track the fact that we're still waiting for auth to complete.
2222 is_auth_in_progress_ = true;
2226 void ProfileSyncService::GoogleSignedOut(const std::string& account_id,
2227 const std::string& username) {
2228 sync_disabled_by_admin_ = false;
2229 DisableForUser();
2231 if (browser_sync::BackupRollbackController::IsBackupEnabled()) {
2232 need_backup_ = true;
2233 backup_finished_ = false;
2237 void ProfileSyncService::AddObserver(
2238 sync_driver::SyncServiceObserver* observer) {
2239 observers_.AddObserver(observer);
2242 void ProfileSyncService::RemoveObserver(
2243 sync_driver::SyncServiceObserver* observer) {
2244 observers_.RemoveObserver(observer);
2247 void ProfileSyncService::AddProtocolEventObserver(
2248 browser_sync::ProtocolEventObserver* observer) {
2249 protocol_event_observers_.AddObserver(observer);
2250 if (HasSyncingBackend()) {
2251 backend_->RequestBufferedProtocolEventsAndEnableForwarding();
2255 void ProfileSyncService::RemoveProtocolEventObserver(
2256 browser_sync::ProtocolEventObserver* observer) {
2257 protocol_event_observers_.RemoveObserver(observer);
2258 if (HasSyncingBackend() &&
2259 !protocol_event_observers_.might_have_observers()) {
2260 backend_->DisableProtocolEventForwarding();
2264 void ProfileSyncService::AddTypeDebugInfoObserver(
2265 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2266 type_debug_info_observers_.AddObserver(type_debug_info_observer);
2267 if (type_debug_info_observers_.might_have_observers() &&
2268 backend_initialized_) {
2269 backend_->EnableDirectoryTypeDebugInfoForwarding();
2273 void ProfileSyncService::RemoveTypeDebugInfoObserver(
2274 syncer::TypeDebugInfoObserver* type_debug_info_observer) {
2275 type_debug_info_observers_.RemoveObserver(type_debug_info_observer);
2276 if (!type_debug_info_observers_.might_have_observers() &&
2277 backend_initialized_) {
2278 backend_->DisableDirectoryTypeDebugInfoForwarding();
2282 void ProfileSyncService::AddPreferenceProvider(
2283 SyncTypePreferenceProvider* provider) {
2284 DCHECK(!HasPreferenceProvider(provider))
2285 << "Providers may only be added once!";
2286 preference_providers_.insert(provider);
2289 void ProfileSyncService::RemovePreferenceProvider(
2290 SyncTypePreferenceProvider* provider) {
2291 DCHECK(HasPreferenceProvider(provider))
2292 << "Only providers that have been added before can be removed!";
2293 preference_providers_.erase(provider);
2296 bool ProfileSyncService::HasPreferenceProvider(
2297 SyncTypePreferenceProvider* provider) const {
2298 return preference_providers_.count(provider) > 0;
2301 namespace {
2303 class GetAllNodesRequestHelper
2304 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> {
2305 public:
2306 GetAllNodesRequestHelper(
2307 syncer::ModelTypeSet requested_types,
2308 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback);
2310 void OnReceivedNodesForTypes(
2311 const std::vector<syncer::ModelType>& types,
2312 ScopedVector<base::ListValue> scoped_node_lists);
2314 private:
2315 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>;
2316 virtual ~GetAllNodesRequestHelper();
2318 scoped_ptr<base::ListValue> result_accumulator_;
2320 syncer::ModelTypeSet awaiting_types_;
2321 base::Callback<void(scoped_ptr<base::ListValue>)> callback_;
2324 GetAllNodesRequestHelper::GetAllNodesRequestHelper(
2325 syncer::ModelTypeSet requested_types,
2326 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback)
2327 : result_accumulator_(new base::ListValue()),
2328 awaiting_types_(requested_types),
2329 callback_(callback) {}
2331 GetAllNodesRequestHelper::~GetAllNodesRequestHelper() {
2332 if (!awaiting_types_.Empty()) {
2333 DLOG(WARNING)
2334 << "GetAllNodesRequest deleted before request was fulfilled. "
2335 << "Missing types are: " << ModelTypeSetToString(awaiting_types_);
2339 // Called when the set of nodes for a type or set of types has been returned.
2341 // The nodes for several types can be returned at the same time by specifying
2342 // their types in the |types| array, and putting their results at the
2343 // correspnding indices in the |scoped_node_lists|.
2344 void GetAllNodesRequestHelper::OnReceivedNodesForTypes(
2345 const std::vector<syncer::ModelType>& types,
2346 ScopedVector<base::ListValue> scoped_node_lists) {
2347 DCHECK_EQ(types.size(), scoped_node_lists.size());
2349 // Take unsafe ownership of the node list.
2350 std::vector<base::ListValue*> node_lists;
2351 scoped_node_lists.release(&node_lists);
2353 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) {
2354 const ModelType type = types[i];
2355 base::ListValue* node_list = node_lists[i];
2357 // Add these results to our list.
2358 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue());
2359 type_dict->SetString("type", ModelTypeToString(type));
2360 type_dict->Set("nodes", node_list);
2361 result_accumulator_->Append(type_dict.release());
2363 // Remember that this part of the request is satisfied.
2364 awaiting_types_.Remove(type);
2367 if (awaiting_types_.Empty()) {
2368 callback_.Run(result_accumulator_.Pass());
2369 callback_.Reset();
2373 } // namespace
2375 void ProfileSyncService::GetAllNodes(
2376 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) {
2377 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes();
2378 directory_types.PutAll(syncer::ControlTypes());
2379 scoped_refptr<GetAllNodesRequestHelper> helper =
2380 new GetAllNodesRequestHelper(directory_types, callback);
2382 if (!backend_initialized_) {
2383 // If there's no backend available to fulfill the request, handle it here.
2384 ScopedVector<base::ListValue> empty_results;
2385 std::vector<ModelType> type_vector;
2386 for (ModelTypeSet::Iterator it = directory_types.First();
2387 it.Good(); it.Inc()) {
2388 type_vector.push_back(it.Get());
2389 empty_results.push_back(new base::ListValue());
2391 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass());
2392 } else {
2393 backend_->GetAllNodesForTypes(
2394 directory_types,
2395 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper));
2399 bool ProfileSyncService::HasObserver(
2400 const sync_driver::SyncServiceObserver* observer) const {
2401 return observers_.HasObserver(observer);
2404 base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() {
2405 return sync_js_controller_.AsWeakPtr();
2408 void ProfileSyncService::SyncEvent(SyncEventCodes code) {
2409 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE);
2412 // static
2413 bool ProfileSyncService::IsSyncEnabled() {
2414 // We have switches::kEnableSync just in case we need to change back to
2415 // sync-disabled-by-default on a platform.
2416 return !base::CommandLine::ForCurrentProcess()->HasSwitch(
2417 switches::kDisableSync);
2420 bool ProfileSyncService::IsManaged() const {
2421 return sync_prefs_.IsManaged() || sync_disabled_by_admin_;
2424 void ProfileSyncService::StopAndSuppress() {
2425 sync_prefs_.SetStartSuppressed(true);
2426 if (HasSyncingBackend()) {
2427 backend_->UnregisterInvalidationIds();
2429 ShutdownImpl(syncer::STOP_SYNC);
2432 bool ProfileSyncService::IsStartSuppressed() const {
2433 return sync_prefs_.IsStartSuppressed();
2436 SigninManagerBase* ProfileSyncService::signin() const {
2437 if (!signin_)
2438 return NULL;
2439 return signin_->GetOriginal();
2442 void ProfileSyncService::UnsuppressAndStart() {
2443 DCHECK(profile_);
2444 sync_prefs_.SetStartSuppressed(false);
2445 DCHECK(!signin_.get() || signin_->GetOriginal()->IsAuthenticated());
2446 startup_controller_->TryStart();
2449 void ProfileSyncService::ReconfigureDatatypeManager() {
2450 // If we haven't initialized yet, don't configure the DTM as it could cause
2451 // association to start before a Directory has even been created.
2452 if (backend_initialized_) {
2453 DCHECK(backend_.get());
2454 ConfigureDataTypeManager();
2455 } else if (HasUnrecoverableError()) {
2456 // There is nothing more to configure. So inform the listeners,
2457 NotifyObservers();
2459 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an "
2460 << "Unrecoverable error.";
2461 } else {
2462 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not "
2463 << "initialized";
2467 syncer::ModelTypeSet ProfileSyncService::GetDataTypesFromPreferenceProviders()
2468 const {
2469 syncer::ModelTypeSet types;
2470 for (std::set<SyncTypePreferenceProvider*>::const_iterator it =
2471 preference_providers_.begin();
2472 it != preference_providers_.end();
2473 ++it) {
2474 types.PutAll((*it)->GetPreferredDataTypes());
2476 return types;
2479 const DataTypeStatusTable& ProfileSyncService::data_type_status_table()
2480 const {
2481 return data_type_status_table_;
2484 void ProfileSyncService::OnInternalUnrecoverableError(
2485 const tracked_objects::Location& from_here,
2486 const std::string& message,
2487 bool delete_sync_database,
2488 UnrecoverableErrorReason reason) {
2489 DCHECK(!HasUnrecoverableError());
2490 unrecoverable_error_reason_ = reason;
2491 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database);
2494 syncer::SyncManagerFactory::MANAGER_TYPE
2495 ProfileSyncService::GetManagerType() const {
2496 switch (backend_mode_) {
2497 case SYNC:
2498 return syncer::SyncManagerFactory::NORMAL;
2499 case BACKUP:
2500 return syncer::SyncManagerFactory::BACKUP;
2501 case ROLLBACK:
2502 return syncer::SyncManagerFactory::ROLLBACK;
2503 case IDLE:
2504 NOTREACHED();
2506 return syncer::SyncManagerFactory::NORMAL;
2509 bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const {
2510 return request_access_token_retry_timer_.IsRunning();
2513 std::string ProfileSyncService::GetAccessTokenForTest() const {
2514 return access_token_;
2517 WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() {
2518 return MakeWeakHandle(sync_js_controller_.AsWeakPtr());
2521 syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() {
2522 return sessions_sync_manager_.get();
2525 syncer::SyncableService* ProfileSyncService::GetDeviceInfoSyncableService() {
2526 return device_info_sync_service_.get();
2529 ProfileSyncService::SyncTokenStatus::SyncTokenStatus()
2530 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED),
2531 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {}
2532 ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {}
2534 ProfileSyncService::SyncTokenStatus
2535 ProfileSyncService::GetSyncTokenStatus() const {
2536 SyncTokenStatus status;
2537 status.connection_status_update_time = connection_status_update_time_;
2538 status.connection_status = connection_status_;
2539 status.token_request_time = token_request_time_;
2540 status.token_receive_time = token_receive_time_;
2541 status.last_get_token_error = last_get_token_error_;
2542 if (request_access_token_retry_timer_.IsRunning())
2543 status.next_token_request_time = next_token_request_time_;
2544 return status;
2547 void ProfileSyncService::OverrideNetworkResourcesForTest(
2548 scoped_ptr<syncer::NetworkResources> network_resources) {
2549 network_resources_ = network_resources.Pass();
2552 bool ProfileSyncService::HasSyncingBackend() const {
2553 return backend_mode_ != SYNC ? false : backend_ != NULL;
2556 void ProfileSyncService::UpdateFirstSyncTimePref() {
2557 if (signin_->GetEffectiveUsername().empty()) {
2558 // Clear if user's not signed in and rollback is done.
2559 if (backend_mode_ != ROLLBACK)
2560 sync_prefs_.ClearFirstSyncTime();
2561 } else if (sync_prefs_.GetFirstSyncTime().is_null() &&
2562 backend_mode_ == SYNC) {
2563 // Set if not set before and it's syncing now.
2564 sync_prefs_.SetFirstSyncTime(base::Time::Now());
2568 void ProfileSyncService::ClearBrowsingDataSinceFirstSync() {
2569 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime();
2570 if (first_sync_time.is_null())
2571 return;
2573 clear_browsing_data_.Run(browsing_data_remover_observer_,
2574 profile_,
2575 first_sync_time,
2576 base::Time::Now());
2579 void ProfileSyncService::SetBrowsingDataRemoverObserverForTesting(
2580 BrowsingDataRemover::Observer* observer) {
2581 browsing_data_remover_observer_ = observer;
2584 void ProfileSyncService::SetClearingBrowseringDataForTesting(
2585 base::Callback<void(BrowsingDataRemover::Observer* observer,
2586 Profile*,
2587 base::Time,
2588 base::Time)> c) {
2589 clear_browsing_data_ = c;
2592 GURL ProfileSyncService::GetSyncServiceURL(
2593 const base::CommandLine& command_line) {
2594 // By default, dev, canary, and unbranded Chromium users will go to the
2595 // development servers. Development servers have more features than standard
2596 // sync servers. Users with officially-branded Chrome stable and beta builds
2597 // will go to the standard sync servers.
2598 GURL result(kDevServerUrl);
2600 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel();
2601 if (channel == chrome::VersionInfo::CHANNEL_STABLE ||
2602 channel == chrome::VersionInfo::CHANNEL_BETA) {
2603 result = GURL(kSyncServerUrl);
2606 // Override the sync server URL from the command-line, if sync server
2607 // command-line argument exists.
2608 if (command_line.HasSwitch(switches::kSyncServiceURL)) {
2609 std::string value(command_line.GetSwitchValueASCII(
2610 switches::kSyncServiceURL));
2611 if (!value.empty()) {
2612 GURL custom_sync_url(value);
2613 if (custom_sync_url.is_valid()) {
2614 result = custom_sync_url;
2615 } else {
2616 LOG(WARNING) << "The following sync URL specified at the command-line "
2617 << "is invalid: " << value;
2621 return result;
2624 void ProfileSyncService::CheckSyncBackupIfNeeded() {
2625 DCHECK_EQ(backend_mode_, SYNC);
2627 #if defined(ENABLE_PRE_SYNC_BACKUP)
2628 const base::Time last_synced_time = sync_prefs_.GetLastSyncedTime();
2629 // Check backup once a day.
2630 if (!last_backup_time_ &&
2631 (last_synced_time.is_null() ||
2632 base::Time::Now() - last_synced_time >=
2633 base::TimeDelta::FromDays(1))) {
2634 // If sync thread is set, need to serialize check on sync thread after
2635 // closing backup DB.
2636 if (sync_thread_) {
2637 sync_thread_->message_loop_proxy()->PostTask(
2638 FROM_HERE,
2639 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2640 profile_->GetPath().Append(kSyncBackupDataFolderName),
2641 base::MessageLoopProxy::current(),
2642 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2643 weak_factory_.GetWeakPtr())));
2644 } else {
2645 content::BrowserThread::PostTask(
2646 content::BrowserThread::FILE, FROM_HERE,
2647 base::Bind(syncer::CheckSyncDbLastModifiedTime,
2648 profile_->GetPath().Append(kSyncBackupDataFolderName),
2649 base::MessageLoopProxy::current(),
2650 base::Bind(&ProfileSyncService::CheckSyncBackupCallback,
2651 weak_factory_.GetWeakPtr())));
2654 #endif
2657 void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) {
2658 last_backup_time_.reset(new base::Time(backup_time));
2660 DCHECK(device_info_sync_service_);
2661 device_info_sync_service_->UpdateLocalDeviceBackupTime(*last_backup_time_);
2664 void ProfileSyncService::TryStartSyncAfterBackup() {
2665 startup_controller_->Reset(GetRegisteredDataTypes());
2666 startup_controller_->TryStart();
2669 void ProfileSyncService::CleanUpBackup() {
2670 sync_prefs_.ClearFirstSyncTime();
2671 profile_->GetIOTaskRunner()->PostTask(
2672 FROM_HERE,
2673 base::Bind(base::IgnoreResult(base::DeleteFile),
2674 profile_->GetPath().Append(kSyncBackupDataFolderName),
2675 true));
2678 bool ProfileSyncService::NeedBackup() const {
2679 return need_backup_;
2682 base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const {
2683 return device_info_sync_service_->GetLocalDeviceBackupTime();
2686 void ProfileSyncService::FlushDirectory() const {
2687 // backend_initialized_ implies backend_ isn't NULL and the manager exists.
2688 // If sync is not initialized yet, we fail silently.
2689 if (backend_initialized_)
2690 backend_->FlushDirectory();
2693 base::FilePath ProfileSyncService::GetDirectoryPathForTest() const {
2694 return directory_path_;
2697 base::MessageLoop* ProfileSyncService::GetSyncLoopForTest() const {
2698 if (sync_thread_) {
2699 return sync_thread_->message_loop();
2700 } else if (backend_) {
2701 return backend_->GetSyncLoopForTesting();
2702 } else {
2703 return NULL;
2707 void ProfileSyncService::RemoveClientFromServer() const {
2708 if (!backend_initialized_) return;
2709 const std::string cache_guid = local_device_->GetLocalSyncCacheGUID();
2710 std::string birthday;
2711 syncer::UserShare* user_share = GetUserShare();
2712 if (user_share && user_share->directory.get()) {
2713 birthday = user_share->directory->store_birthday();
2715 if (!access_token_.empty() && !cache_guid.empty() && !birthday.empty()) {
2716 sync_stopped_reporter_->ReportSyncStopped(
2717 access_token_, cache_guid, birthday);