profile_sync_service.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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. 4 5#include "chrome/browser/sync/profile_sync_service.h" 6 7#include <cstddef> 8#include <map> 9#include <set> 10#include <utility> 11 12#include "base/basictypes.h" 13#include "base/bind.h" 14#include "base/bind_helpers.h" 15#include "base/callback.h" 16#include "base/command_line.h" 17#include "base/compiler_specific.h" 18#include "base/file_util.h" 19#include "base/logging.h" 20#include "base/memory/ref_counted.h" 21#include "base/message_loop/message_loop.h" 22#include "base/metrics/histogram.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/bookmarks/enhanced_bookmarks_features.h" 28#include "chrome/browser/browser_process.h" 29#include "chrome/browser/browsing_data/browsing_data_helper.h" 30#include "chrome/browser/browsing_data/browsing_data_remover.h" 31#include "chrome/browser/chrome_notification_types.h" 32#include "chrome/browser/defaults.h" 33#include "chrome/browser/invalidation/profile_invalidation_provider_factory.h" 34#include "chrome/browser/net/chrome_cookie_notification_details.h" 35#include "chrome/browser/prefs/chrome_pref_service_factory.h" 36#include "chrome/browser/prefs/pref_service_syncable.h" 37#include "chrome/browser/profiles/profile.h" 38#include "chrome/browser/services/gcm/gcm_profile_service.h" 39#include "chrome/browser/services/gcm/gcm_profile_service_factory.h" 40#include "chrome/browser/signin/about_signin_internals_factory.h" 41#include "chrome/browser/signin/profile_oauth2_token_service_factory.h" 42#include "chrome/browser/signin/signin_manager_factory.h" 43#include "chrome/browser/sync/backend_migrator.h" 44#include "chrome/browser/sync/glue/chrome_report_unrecoverable_error.h" 45#include "chrome/browser/sync/glue/device_info.h" 46#include "chrome/browser/sync/glue/favicon_cache.h" 47#include "chrome/browser/sync/glue/sync_backend_host.h" 48#include "chrome/browser/sync/glue/sync_backend_host_impl.h" 49#include "chrome/browser/sync/glue/sync_start_util.h" 50#include "chrome/browser/sync/glue/synced_device_tracker.h" 51#include "chrome/browser/sync/glue/typed_url_data_type_controller.h" 52#include "chrome/browser/sync/profile_sync_components_factory_impl.h" 53#include "chrome/browser/sync/sessions/notification_service_sessions_router.h" 54#include "chrome/browser/sync/sessions/sessions_sync_manager.h" 55#include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h" 56#include "chrome/browser/sync/sync_error_controller.h" 57#include "chrome/browser/ui/browser.h" 58#include "chrome/browser/ui/browser_list.h" 59#include "chrome/browser/ui/browser_window.h" 60#include "chrome/browser/ui/global_error/global_error_service.h" 61#include "chrome/browser/ui/global_error/global_error_service_factory.h" 62#include "chrome/common/chrome_switches.h" 63#include "chrome/common/chrome_version_info.h" 64#include "chrome/common/pref_names.h" 65#include "chrome/common/url_constants.h" 66#include "components/gcm_driver/gcm_driver.h" 67#include "components/invalidation/invalidation_service.h" 68#include "components/invalidation/profile_invalidation_provider.h" 69#include "components/pref_registry/pref_registry_syncable.h" 70#include "components/signin/core/browser/about_signin_internals.h" 71#include "components/signin/core/browser/profile_oauth2_token_service.h" 72#include "components/signin/core/browser/signin_manager.h" 73#include "components/signin/core/browser/signin_metrics.h" 74#include "components/sync_driver/change_processor.h" 75#include "components/sync_driver/data_type_controller.h" 76#include "components/sync_driver/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 "grit/generated_resources.h" 84#include "net/cookies/cookie_monster.h" 85#include "net/url_request/url_request_context_getter.h" 86#include "sync/api/sync_error.h" 87#include "sync/internal_api/public/configure_reason.h" 88#include "sync/internal_api/public/http_bridge_network_resources.h" 89#include "sync/internal_api/public/network_resources.h" 90#include "sync/internal_api/public/sessions/type_debug_info_observer.h" 91#include "sync/internal_api/public/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/util/cryptographer.h" 98#include "ui/base/l10n/l10n_util.h" 99#include "ui/base/l10n/time_format.h" 100 101#if defined(OS_ANDROID) 102#include "sync/internal_api/public/read_transaction.h" 103#endif 104 105using browser_sync::ChangeProcessor; 106using browser_sync::DataTypeController; 107using browser_sync::DataTypeManager; 108using browser_sync::FailedDataTypesHandler; 109using browser_sync::NotificationServiceSessionsRouter; 110using browser_sync::ProfileSyncServiceStartBehavior; 111using browser_sync::SyncBackendHost; 112using syncer::ModelType; 113using syncer::ModelTypeSet; 114using syncer::JsBackend; 115using syncer::JsController; 116using syncer::JsEventDetails; 117using syncer::JsEventHandler; 118using syncer::ModelSafeRoutingInfo; 119using syncer::SyncCredentials; 120using syncer::SyncProtocolError; 121using syncer::WeakHandle; 122 123typedef GoogleServiceAuthError AuthError; 124 125const char* ProfileSyncService::kSyncServerUrl = 126 "https://clients4.google.com/chrome-sync"; 127 128const char* ProfileSyncService::kDevServerUrl = 129 "https://clients4.google.com/chrome-sync/dev"; 130 131const char kSyncUnrecoverableErrorHistogram[] = 132 "Sync.UnrecoverableErrors"; 133 134const net::BackoffEntry::Policy kRequestAccessTokenBackoffPolicy = { 135 // Number of initial errors (in sequence) to ignore before applying 136 // exponential back-off rules. 137 0, 138 139 // Initial delay for exponential back-off in ms. 140 2000, 141 142 // Factor by which the waiting time will be multiplied. 143 2, 144 145 // Fuzzing percentage. ex: 10% will spread requests randomly 146 // between 90%-100% of the calculated time. 147 0.2, // 20% 148 149 // Maximum amount of time we are willing to delay our request in ms. 150 // TODO(pavely): crbug.com/246686 ProfileSyncService should retry 151 // RequestAccessToken on connection state change after backoff 152 1000 * 3600 * 4, // 4 hours. 153 154 // Time to keep an entry from being discarded even when it 155 // has no significant state, -1 to never discard. 156 -1, 157 158 // Don't use initial delay unless the last request was an error. 159 false, 160}; 161 162static const base::FilePath::CharType kSyncDataFolderName[] = 163 FILE_PATH_LITERAL("Sync Data"); 164 165static const base::FilePath::CharType kSyncBackupDataFolderName[] = 166 FILE_PATH_LITERAL("Sync Data Backup"); 167 168// Default delay in seconds to start backup/rollback backend. 169const int kBackupStartDelay = 10; 170 171namespace { 172 173void ClearBrowsingData(Profile* profile, base::Time start, base::Time end) { 174 // BrowsingDataRemover deletes itself when it's done. 175 BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange( 176 profile, start, end); 177 remover->Remove(BrowsingDataRemover::REMOVE_ALL, 178 BrowsingDataHelper::ALL); 179} 180 181} // anonymous namespace 182 183bool ShouldShowActionOnUI( 184 const syncer::SyncProtocolError& error) { 185 return (error.action != syncer::UNKNOWN_ACTION && 186 error.action != syncer::DISABLE_SYNC_ON_CLIENT && 187 error.action != syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT); 188} 189 190ProfileSyncService::ProfileSyncService( 191 ProfileSyncComponentsFactory* factory, 192 Profile* profile, 193 scoped_ptr<SupervisedUserSigninManagerWrapper> signin_wrapper, 194 ProfileOAuth2TokenService* oauth2_token_service, 195 ProfileSyncServiceStartBehavior start_behavior) 196 : OAuth2TokenService::Consumer("sync"), 197 last_auth_error_(AuthError::AuthErrorNone()), 198 passphrase_required_reason_(syncer::REASON_PASSPHRASE_NOT_REQUIRED), 199 factory_(factory), 200 profile_(profile), 201 sync_prefs_(profile_->GetPrefs()), 202 sync_service_url_(GetSyncServiceURL(*CommandLine::ForCurrentProcess())), 203 is_first_time_sync_configure_(false), 204 backend_initialized_(false), 205 sync_disabled_by_admin_(false), 206 is_auth_in_progress_(false), 207 signin_(signin_wrapper.Pass()), 208 unrecoverable_error_reason_(ERROR_REASON_UNSET), 209 expect_sync_configuration_aborted_(false), 210 encrypted_types_(syncer::SyncEncryptionHandler::SensitiveTypes()), 211 encrypt_everything_(false), 212 encryption_pending_(false), 213 configure_status_(DataTypeManager::UNKNOWN), 214 oauth2_token_service_(oauth2_token_service), 215 request_access_token_backoff_(&kRequestAccessTokenBackoffPolicy), 216 weak_factory_(this), 217 startup_controller_weak_factory_(this), 218 connection_status_(syncer::CONNECTION_NOT_ATTEMPTED), 219 last_get_token_error_(GoogleServiceAuthError::AuthErrorNone()), 220 network_resources_(new syncer::HttpBridgeNetworkResources), 221 startup_controller_( 222 start_behavior, 223 oauth2_token_service, 224 &sync_prefs_, 225 signin_.get(), 226 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents, 227 startup_controller_weak_factory_.GetWeakPtr(), 228 SYNC)), 229 backup_rollback_controller_( 230 &sync_prefs_, 231 signin_.get(), 232 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents, 233 startup_controller_weak_factory_.GetWeakPtr(), 234 BACKUP), 235 base::Bind(&ProfileSyncService::StartUpSlowBackendComponents, 236 startup_controller_weak_factory_.GetWeakPtr(), 237 ROLLBACK)), 238 backend_mode_(IDLE), 239 backup_start_delay_(base::TimeDelta::FromSeconds(kBackupStartDelay)), 240 clear_browsing_data_(base::Bind(&ClearBrowsingData)) { 241 DCHECK(profile); 242 syncer::SyncableService::StartSyncFlare flare( 243 sync_start_util::GetFlareForSyncableService(profile->GetPath())); 244 scoped_ptr<browser_sync::LocalSessionEventRouter> router( 245 new NotificationServiceSessionsRouter(profile, flare)); 246 sessions_sync_manager_.reset( 247 new SessionsSyncManager(profile, this, router.Pass())); 248} 249 250ProfileSyncService::~ProfileSyncService() { 251 sync_prefs_.RemoveSyncPrefObserver(this); 252 // Shutdown() should have been called before destruction. 253 CHECK(!backend_initialized_); 254} 255 256bool ProfileSyncService::IsSyncEnabledAndLoggedIn() { 257 // Exit if sync is disabled. 258 if (IsManaged() || sync_prefs_.IsStartSuppressed()) 259 return false; 260 261 // Sync is logged in if there is a non-empty effective username. 262 return !signin_->GetEffectiveUsername().empty(); 263} 264 265bool ProfileSyncService::IsOAuthRefreshTokenAvailable() { 266 if (!oauth2_token_service_) 267 return false; 268 269 return oauth2_token_service_->RefreshTokenIsAvailable( 270 signin_->GetAccountIdToUse()); 271} 272 273void ProfileSyncService::Initialize() { 274 // We clear this here (vs Shutdown) because we want to remember that an error 275 // happened on shutdown so we can display details (message, location) about it 276 // in about:sync. 277 ClearStaleErrors(); 278 279 sync_prefs_.AddSyncPrefObserver(this); 280 281 // For now, the only thing we can do through policy is to turn sync off. 282 if (IsManaged()) { 283 DisableForUser(); 284 return; 285 } 286 287 RegisterAuthNotifications(); 288 289 if (!HasSyncSetupCompleted() || signin_->GetEffectiveUsername().empty()) { 290 // Clean up in case of previous crash / setup abort / signout. 291 DisableForUser(); 292 } 293 294 TrySyncDatatypePrefRecovery(); 295 296 last_synced_time_ = sync_prefs_.GetLastSyncedTime(); 297 298#if defined(OS_CHROMEOS) 299 std::string bootstrap_token = sync_prefs_.GetEncryptionBootstrapToken(); 300 if (bootstrap_token.empty()) { 301 sync_prefs_.SetEncryptionBootstrapToken( 302 sync_prefs_.GetSpareBootstrapToken()); 303 } 304#endif 305 306#if !defined(OS_ANDROID) 307 DCHECK(sync_error_controller_ == NULL) 308 << "Initialize() called more than once."; 309 sync_error_controller_.reset(new SyncErrorController(this)); 310 AddObserver(sync_error_controller_.get()); 311#endif 312 313 startup_controller_.Reset(GetRegisteredDataTypes()); 314 startup_controller_.TryStart(); 315 316 317 if (browser_sync::BackupRollbackController::IsBackupEnabled()) { 318 backup_rollback_controller_.Start(backup_start_delay_); 319 } else { 320#if defined(ENABLE_PRE_SYNC_BACKUP) 321 profile_->GetIOTaskRunner()->PostDelayedTask( 322 FROM_HERE, 323 base::Bind(base::IgnoreResult(base::DeleteFile), 324 profile_->GetPath().Append(kSyncBackupDataFolderName), 325 true), 326 backup_start_delay_); 327#endif 328 } 329} 330 331void ProfileSyncService::TrySyncDatatypePrefRecovery() { 332 DCHECK(!sync_initialized()); 333 if (!HasSyncSetupCompleted()) 334 return; 335 336 // There was a bug where OnUserChoseDatatypes was not properly called on 337 // configuration (see crbug.com/154940). We detect this by checking whether 338 // kSyncKeepEverythingSynced has a default value. If so, and sync setup has 339 // completed, it means sync was not properly configured, so we manually 340 // set kSyncKeepEverythingSynced. 341 PrefService* const pref_service = profile_->GetPrefs(); 342 if (!pref_service) 343 return; 344 if (GetPreferredDataTypes().Size() > 1) 345 return; 346 347 const PrefService::Preference* keep_everything_synced = 348 pref_service->FindPreference( 349 sync_driver::prefs::kSyncKeepEverythingSynced); 350 // This will be false if the preference was properly set or if it's controlled 351 // by policy. 352 if (!keep_everything_synced->IsDefaultValue()) 353 return; 354 355 // kSyncKeepEverythingSynced was not properly set. Set it and the preferred 356 // types now, before we configure. 357 UMA_HISTOGRAM_COUNTS("Sync.DatatypePrefRecovery", 1); 358 sync_prefs_.SetKeepEverythingSynced(true); 359 syncer::ModelTypeSet registered_types = GetRegisteredDataTypes(); 360 sync_prefs_.SetPreferredDataTypes(registered_types, 361 registered_types); 362} 363 364void ProfileSyncService::StartSyncingWithServer() { 365 if (backend_) 366 backend_->StartSyncingWithServer(); 367} 368 369void ProfileSyncService::RegisterAuthNotifications() { 370 oauth2_token_service_->AddObserver(this); 371 if (signin()) 372 signin()->AddObserver(this); 373} 374 375void ProfileSyncService::UnregisterAuthNotifications() { 376 if (signin()) 377 signin()->RemoveObserver(this); 378 oauth2_token_service_->RemoveObserver(this); 379} 380 381void ProfileSyncService::RegisterDataTypeController( 382 DataTypeController* data_type_controller) { 383 DCHECK_EQ( 384 directory_data_type_controllers_.count(data_type_controller->type()), 385 0U); 386 DCHECK(!GetRegisteredNonBlockingDataTypes().Has( 387 data_type_controller->type())); 388 directory_data_type_controllers_[data_type_controller->type()] = 389 data_type_controller; 390} 391 392void ProfileSyncService::RegisterNonBlockingType(syncer::ModelType type) { 393 DCHECK_EQ(directory_data_type_controllers_.count(type), 0U) 394 << "Duplicate registration of type " << ModelTypeToString(type); 395 396 // TODO(rlarocque): Set the enable flag properly when crbug.com/368834 is 397 // fixed and we have some way of telling whether or not this type should be 398 // enabled. 399 non_blocking_data_type_manager_.RegisterType(type, false); 400} 401 402void ProfileSyncService::InitializeNonBlockingType( 403 syncer::ModelType type, 404 const scoped_refptr<base::SequencedTaskRunner>& task_runner, 405 const base::WeakPtr<syncer::ModelTypeSyncProxyImpl>& type_sync_proxy) { 406 non_blocking_data_type_manager_.InitializeType( 407 type, task_runner, type_sync_proxy); 408} 409 410bool ProfileSyncService::IsSessionsDataTypeControllerRunning() const { 411 return directory_data_type_controllers_.find(syncer::SESSIONS) != 412 directory_data_type_controllers_.end() && 413 (directory_data_type_controllers_.find(syncer::SESSIONS)-> 414 second->state() == DataTypeController::RUNNING); 415} 416 417browser_sync::OpenTabsUIDelegate* ProfileSyncService::GetOpenTabsUIDelegate() { 418 if (!IsSessionsDataTypeControllerRunning()) 419 return NULL; 420 return sessions_sync_manager_.get(); 421} 422 423browser_sync::FaviconCache* ProfileSyncService::GetFaviconCache() { 424 return sessions_sync_manager_->GetFaviconCache(); 425} 426 427scoped_ptr<browser_sync::DeviceInfo> 428ProfileSyncService::GetLocalDeviceInfo() const { 429 if (HasSyncingBackend()) { 430 browser_sync::SyncedDeviceTracker* device_tracker = 431 backend_->GetSyncedDeviceTracker(); 432 if (device_tracker) 433 return device_tracker->ReadLocalDeviceInfo(); 434 } 435 return scoped_ptr<browser_sync::DeviceInfo>(); 436} 437 438scoped_ptr<browser_sync::DeviceInfo> 439ProfileSyncService::GetDeviceInfo(const std::string& client_id) const { 440 if (HasSyncingBackend()) { 441 browser_sync::SyncedDeviceTracker* device_tracker = 442 backend_->GetSyncedDeviceTracker(); 443 if (device_tracker) 444 return device_tracker->ReadDeviceInfo(client_id); 445 } 446 return scoped_ptr<browser_sync::DeviceInfo>(); 447} 448 449ScopedVector<browser_sync::DeviceInfo> 450 ProfileSyncService::GetAllSignedInDevices() const { 451 ScopedVector<browser_sync::DeviceInfo> devices; 452 if (HasSyncingBackend()) { 453 browser_sync::SyncedDeviceTracker* device_tracker = 454 backend_->GetSyncedDeviceTracker(); 455 if (device_tracker) { 456 // TODO(lipalani) - Make device tracker return a scoped vector. 457 device_tracker->GetAllSyncedDeviceInfo(&devices); 458 } 459 } 460 return devices.Pass(); 461} 462 463std::string ProfileSyncService::GetLocalSyncCacheGUID() const { 464 if (HasSyncingBackend()) { 465 browser_sync::SyncedDeviceTracker* device_tracker = 466 backend_->GetSyncedDeviceTracker(); 467 if (device_tracker) { 468 return device_tracker->cache_guid(); 469 } 470 } 471 return std::string(); 472} 473 474// Notifies the observer of any device info changes. 475void ProfileSyncService::AddObserverForDeviceInfoChange( 476 browser_sync::SyncedDeviceTracker::Observer* observer) { 477 if (HasSyncingBackend()) { 478 browser_sync::SyncedDeviceTracker* device_tracker = 479 backend_->GetSyncedDeviceTracker(); 480 if (device_tracker) { 481 device_tracker->AddObserver(observer); 482 } 483 } 484} 485 486// Removes the observer from device info change notification. 487void ProfileSyncService::RemoveObserverForDeviceInfoChange( 488 browser_sync::SyncedDeviceTracker::Observer* observer) { 489 if (HasSyncingBackend()) { 490 browser_sync::SyncedDeviceTracker* device_tracker = 491 backend_->GetSyncedDeviceTracker(); 492 if (device_tracker) { 493 device_tracker->RemoveObserver(observer); 494 } 495 } 496} 497 498void ProfileSyncService::GetDataTypeControllerStates( 499 browser_sync::DataTypeController::StateMap* state_map) const { 500 for (browser_sync::DataTypeController::TypeMap::const_iterator iter = 501 directory_data_type_controllers_.begin(); 502 iter != directory_data_type_controllers_.end(); 503 ++iter) 504 (*state_map)[iter->first] = iter->second.get()->state(); 505} 506 507SyncCredentials ProfileSyncService::GetCredentials() { 508 SyncCredentials credentials; 509 if (backend_mode_ == SYNC) { 510 credentials.email = signin_->GetEffectiveUsername(); 511 DCHECK(!credentials.email.empty()); 512 credentials.sync_token = access_token_; 513 514 if (credentials.sync_token.empty()) 515 credentials.sync_token = "credentials_lost"; 516 517 credentials.scope_set.insert(signin_->GetSyncScopeToUse()); 518 } 519 520 return credentials; 521} 522 523bool ProfileSyncService::ShouldDeleteSyncFolder() { 524 if (backend_mode_ == SYNC) 525 return !HasSyncSetupCompleted(); 526 527 if (backend_mode_ == BACKUP) { 528 base::Time reset_time = chrome_prefs::GetResetTime(profile_); 529 530 // Start fresh if: 531 // * It's the first time backup after user stopped syncing because backup 532 // DB may contain items deleted by user during sync period and can cause 533 // back-from-dead issues if user didn't choose rollback. 534 // * Settings are reset during startup because of tampering to avoid 535 // restoring settings from backup. 536 if (!sync_prefs_.GetFirstSyncTime().is_null() || 537 (!reset_time.is_null() && profile_->GetStartTime() <= reset_time)) { 538 return true; 539 } 540 } 541 542 return false; 543} 544 545void ProfileSyncService::InitializeBackend(bool delete_stale_data) { 546 if (!backend_) { 547 NOTREACHED(); 548 return; 549 } 550 551 SyncCredentials credentials = GetCredentials(); 552 553 scoped_refptr<net::URLRequestContextGetter> request_context_getter( 554 profile_->GetRequestContext()); 555 556 if (backend_mode_ == SYNC && delete_stale_data) 557 ClearStaleErrors(); 558 559 scoped_ptr<syncer::UnrecoverableErrorHandler> 560 backend_unrecoverable_error_handler( 561 new browser_sync::BackendUnrecoverableErrorHandler( 562 MakeWeakHandle(weak_factory_.GetWeakPtr()))); 563 564 backend_->Initialize( 565 this, 566 sync_thread_.Pass(), 567 GetJsEventHandler(), 568 sync_service_url_, 569 credentials, 570 delete_stale_data, 571 scoped_ptr<syncer::SyncManagerFactory>( 572 new syncer::SyncManagerFactory(GetManagerType())).Pass(), 573 backend_unrecoverable_error_handler.Pass(), 574 &browser_sync::ChromeReportUnrecoverableError, 575 network_resources_.get()); 576} 577 578bool ProfileSyncService::IsEncryptedDatatypeEnabled() const { 579 if (encryption_pending()) 580 return true; 581 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes(); 582 const syncer::ModelTypeSet encrypted_types = GetEncryptedDataTypes(); 583 DCHECK(encrypted_types.Has(syncer::PASSWORDS)); 584 return !Intersection(preferred_types, encrypted_types).Empty(); 585} 586 587void ProfileSyncService::OnSyncConfigureRetry() { 588 // Note: in order to handle auth failures that arise before the backend is 589 // initialized (e.g. from invalidation notifier, or downloading new control 590 // types), we have to gracefully handle configuration retries at all times. 591 // At this point an auth error badge should be shown, which once resolved 592 // will trigger a new sync cycle. 593 NotifyObservers(); 594} 595 596void ProfileSyncService::OnProtocolEvent( 597 const syncer::ProtocolEvent& event) { 598 FOR_EACH_OBSERVER(browser_sync::ProtocolEventObserver, 599 protocol_event_observers_, 600 OnProtocolEvent(event)); 601} 602 603void ProfileSyncService::OnDirectoryTypeCommitCounterUpdated( 604 syncer::ModelType type, 605 const syncer::CommitCounters& counters) { 606 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver, 607 type_debug_info_observers_, 608 OnCommitCountersUpdated(type, counters)); 609} 610 611void ProfileSyncService::OnDirectoryTypeUpdateCounterUpdated( 612 syncer::ModelType type, 613 const syncer::UpdateCounters& counters) { 614 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver, 615 type_debug_info_observers_, 616 OnUpdateCountersUpdated(type, counters)); 617} 618 619void ProfileSyncService::OnDirectoryTypeStatusCounterUpdated( 620 syncer::ModelType type, 621 const syncer::StatusCounters& counters) { 622 FOR_EACH_OBSERVER(syncer::TypeDebugInfoObserver, 623 type_debug_info_observers_, 624 OnStatusCountersUpdated(type, counters)); 625} 626 627void ProfileSyncService::OnDataTypeRequestsSyncStartup( 628 syncer::ModelType type) { 629 DCHECK(syncer::UserTypes().Has(type)); 630 if (backend_.get()) { 631 DVLOG(1) << "A data type requested sync startup, but it looks like " 632 "something else beat it to the punch."; 633 return; 634 } 635 636 if (!GetPreferredDataTypes().Has(type)) { 637 // We can get here as datatype SyncableServices are typically wired up 638 // to the native datatype even if sync isn't enabled. 639 DVLOG(1) << "Dropping sync startup request because type " 640 << syncer::ModelTypeToString(type) << "not enabled."; 641 return; 642 } 643 644 startup_controller_.OnDataTypeRequestsSyncStartup(type); 645} 646 647void ProfileSyncService::StartUpSlowBackendComponents( 648 ProfileSyncService::BackendMode mode) { 649 DCHECK_NE(IDLE, mode); 650 if (backend_mode_ == mode) { 651 return; 652 } 653 654 DVLOG(1) << "Start backend mode: " << mode; 655 656 if (backend_) 657 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD); 658 659 backend_mode_ = mode; 660 661 if (backend_mode_ == ROLLBACK) 662 ClearBrowsingDataSinceFirstSync(); 663 else if (backend_mode_ == SYNC) 664 CheckSyncBackupIfNeeded(); 665 666 base::FilePath sync_folder = backend_mode_ == SYNC ? 667 base::FilePath(kSyncDataFolderName) : 668 base::FilePath(kSyncBackupDataFolderName); 669 670 invalidation::InvalidationService* invalidator = NULL; 671 if (backend_mode_ == SYNC) { 672 invalidation::ProfileInvalidationProvider* provider = 673 invalidation::ProfileInvalidationProviderFactory::GetForProfile( 674 profile_); 675 if (provider) 676 invalidator = provider->GetInvalidationService(); 677 } 678 679 backend_.reset( 680 factory_->CreateSyncBackendHost( 681 profile_->GetDebugName(), 682 profile_, 683 invalidator, 684 sync_prefs_.AsWeakPtr(), 685 sync_folder)); 686 687 // Initialize the backend. Every time we start up a new SyncBackendHost, 688 // we'll want to start from a fresh SyncDB, so delete any old one that might 689 // be there. 690 InitializeBackend(ShouldDeleteSyncFolder()); 691 692 UpdateFirstSyncTimePref(); 693} 694 695void ProfileSyncService::OnGetTokenSuccess( 696 const OAuth2TokenService::Request* request, 697 const std::string& access_token, 698 const base::Time& expiration_time) { 699 DCHECK_EQ(access_token_request_, request); 700 access_token_request_.reset(); 701 access_token_ = access_token; 702 token_receive_time_ = base::Time::Now(); 703 last_get_token_error_ = GoogleServiceAuthError::AuthErrorNone(); 704 705 if (sync_prefs_.SyncHasAuthError()) { 706 sync_prefs_.SetSyncAuthError(false); 707 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError", 708 AUTH_ERROR_FIXED, 709 AUTH_ERROR_LIMIT); 710 } 711 712 if (HasSyncingBackend()) 713 backend_->UpdateCredentials(GetCredentials()); 714 else 715 startup_controller_.TryStart(); 716} 717 718void ProfileSyncService::OnGetTokenFailure( 719 const OAuth2TokenService::Request* request, 720 const GoogleServiceAuthError& error) { 721 DCHECK_EQ(access_token_request_, request); 722 DCHECK_NE(error.state(), GoogleServiceAuthError::NONE); 723 access_token_request_.reset(); 724 last_get_token_error_ = error; 725 switch (error.state()) { 726 case GoogleServiceAuthError::CONNECTION_FAILED: 727 case GoogleServiceAuthError::SERVICE_UNAVAILABLE: { 728 // Transient error. Retry after some time. 729 request_access_token_backoff_.InformOfRequest(false); 730 next_token_request_time_ = base::Time::Now() + 731 request_access_token_backoff_.GetTimeUntilRelease(); 732 request_access_token_retry_timer_.Start( 733 FROM_HERE, 734 request_access_token_backoff_.GetTimeUntilRelease(), 735 base::Bind(&ProfileSyncService::RequestAccessToken, 736 weak_factory_.GetWeakPtr())); 737 NotifyObservers(); 738 break; 739 } 740 case GoogleServiceAuthError::SERVICE_ERROR: 741 case GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS: { 742 if (!sync_prefs_.SyncHasAuthError()) { 743 sync_prefs_.SetSyncAuthError(true); 744 UMA_HISTOGRAM_ENUMERATION("Sync.SyncAuthError", 745 AUTH_ERROR_ENCOUNTERED, 746 AUTH_ERROR_LIMIT); 747 } 748 // Fallthrough. 749 } 750 default: { 751 // Show error to user. 752 UpdateAuthErrorState(error); 753 } 754 } 755} 756 757void ProfileSyncService::OnRefreshTokenAvailable( 758 const std::string& account_id) { 759 if (account_id == signin_->GetAccountIdToUse()) 760 OnRefreshTokensLoaded(); 761} 762 763void ProfileSyncService::OnRefreshTokenRevoked( 764 const std::string& account_id) { 765 if (!IsOAuthRefreshTokenAvailable()) { 766 access_token_.clear(); 767 // The additional check around IsOAuthRefreshTokenAvailable() above 768 // prevents us sounding the alarm if we actually have a valid token but 769 // a refresh attempt failed for any variety of reasons 770 // (e.g. flaky network). It's possible the token we do have is also 771 // invalid, but in that case we should already have (or can expect) an 772 // auth error sent from the sync backend. 773 UpdateAuthErrorState( 774 GoogleServiceAuthError(GoogleServiceAuthError::REQUEST_CANCELED)); 775 } 776} 777 778void ProfileSyncService::OnRefreshTokensLoaded() { 779 // This notification gets fired when OAuth2TokenService loads the tokens 780 // from storage. 781 // Initialize the backend if sync is enabled. If the sync token was 782 // not loaded, GetCredentials() will generate invalid credentials to 783 // cause the backend to generate an auth error (crbug.com/121755). 784 if (HasSyncingBackend()) { 785 RequestAccessToken(); 786 } else { 787 startup_controller_.TryStart(); 788 } 789} 790 791void ProfileSyncService::Shutdown() { 792 UnregisterAuthNotifications(); 793 794 ShutdownImpl(browser_sync::SyncBackendHost::STOP); 795 if (sync_error_controller_) { 796 // Destroy the SyncErrorController when the service shuts down for good. 797 RemoveObserver(sync_error_controller_.get()); 798 sync_error_controller_.reset(); 799 } 800 801 if (sync_thread_) 802 sync_thread_->Stop(); 803} 804 805void ProfileSyncService::ShutdownImpl( 806 browser_sync::SyncBackendHost::ShutdownOption option) { 807 if (!backend_) 808 return; 809 810 non_blocking_data_type_manager_.DisconnectSyncBackend(); 811 812 // First, we spin down the backend to stop change processing as soon as 813 // possible. 814 base::Time shutdown_start_time = base::Time::Now(); 815 backend_->StopSyncingForShutdown(); 816 817 // Stop all data type controllers, if needed. Note that until Stop 818 // completes, it is possible in theory to have a ChangeProcessor apply a 819 // change from a native model. In that case, it will get applied to the sync 820 // database (which doesn't get destroyed until we destroy the backend below) 821 // as an unsynced change. That will be persisted, and committed on restart. 822 if (directory_data_type_manager_) { 823 if (directory_data_type_manager_->state() != DataTypeManager::STOPPED) { 824 // When aborting as part of shutdown, we should expect an aborted sync 825 // configure result, else we'll dcheck when we try to read the sync error. 826 expect_sync_configuration_aborted_ = true; 827 directory_data_type_manager_->Stop(); 828 } 829 directory_data_type_manager_.reset(); 830 } 831 832 // Shutdown the migrator before the backend to ensure it doesn't pull a null 833 // snapshot. 834 migrator_.reset(); 835 sync_js_controller_.AttachJsBackend(WeakHandle<syncer::JsBackend>()); 836 837 // Move aside the backend so nobody else tries to use it while we are 838 // shutting it down. 839 scoped_ptr<SyncBackendHost> doomed_backend(backend_.release()); 840 if (doomed_backend) { 841 sync_thread_ = doomed_backend->Shutdown(option); 842 doomed_backend.reset(); 843 } 844 base::TimeDelta shutdown_time = base::Time::Now() - shutdown_start_time; 845 UMA_HISTOGRAM_TIMES("Sync.Shutdown.BackendDestroyedTime", shutdown_time); 846 847 weak_factory_.InvalidateWeakPtrs(); 848 849 if (backend_mode_ == SYNC) 850 startup_controller_.Reset(GetRegisteredDataTypes()); 851 852 // Clear various flags. 853 backend_mode_ = IDLE; 854 expect_sync_configuration_aborted_ = false; 855 is_auth_in_progress_ = false; 856 backend_initialized_ = false; 857 cached_passphrase_.clear(); 858 access_token_.clear(); 859 encryption_pending_ = false; 860 encrypt_everything_ = false; 861 encrypted_types_ = syncer::SyncEncryptionHandler::SensitiveTypes(); 862 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED; 863 request_access_token_retry_timer_.Stop(); 864 // Revert to "no auth error". 865 if (last_auth_error_.state() != GoogleServiceAuthError::NONE) 866 UpdateAuthErrorState(GoogleServiceAuthError::AuthErrorNone()); 867 868 NotifyObservers(); 869} 870 871void ProfileSyncService::DisableForUser() { 872 // Clear prefs (including SyncSetupHasCompleted) before shutting down so 873 // PSS clients don't think we're set up while we're shutting down. 874 sync_prefs_.ClearPreferences(); 875 ClearUnrecoverableError(); 876 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD); 877} 878 879bool ProfileSyncService::HasSyncSetupCompleted() const { 880 return sync_prefs_.HasSyncSetupCompleted(); 881} 882 883void ProfileSyncService::SetSyncSetupCompleted() { 884 sync_prefs_.SetSyncSetupCompleted(); 885} 886 887void ProfileSyncService::UpdateLastSyncedTime() { 888 last_synced_time_ = base::Time::Now(); 889 sync_prefs_.SetLastSyncedTime(last_synced_time_); 890} 891 892void ProfileSyncService::NotifyObservers() { 893 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_, 894 OnStateChanged()); 895} 896 897void ProfileSyncService::NotifySyncCycleCompleted() { 898 FOR_EACH_OBSERVER(ProfileSyncServiceBase::Observer, observers_, 899 OnSyncCycleCompleted()); 900} 901 902void ProfileSyncService::ClearStaleErrors() { 903 ClearUnrecoverableError(); 904 last_actionable_error_ = SyncProtocolError(); 905 // Clear the data type errors as well. 906 failed_data_types_handler_.Reset(); 907} 908 909void ProfileSyncService::ClearUnrecoverableError() { 910 unrecoverable_error_reason_ = ERROR_REASON_UNSET; 911 unrecoverable_error_message_.clear(); 912 unrecoverable_error_location_ = tracked_objects::Location(); 913} 914 915void ProfileSyncService::RegisterNewDataType(syncer::ModelType data_type) { 916 if (directory_data_type_controllers_.count(data_type) > 0) 917 return; 918 NOTREACHED(); 919} 920 921// An invariant has been violated. Transition to an error state where we try 922// to do as little work as possible, to avoid further corruption or crashes. 923void ProfileSyncService::OnUnrecoverableError( 924 const tracked_objects::Location& from_here, 925 const std::string& message) { 926 // Unrecoverable errors that arrive via the syncer::UnrecoverableErrorHandler 927 // interface are assumed to originate within the syncer. 928 unrecoverable_error_reason_ = ERROR_REASON_SYNCER; 929 OnUnrecoverableErrorImpl(from_here, message, true); 930} 931 932void ProfileSyncService::OnUnrecoverableErrorImpl( 933 const tracked_objects::Location& from_here, 934 const std::string& message, 935 bool delete_sync_database) { 936 DCHECK(HasUnrecoverableError()); 937 unrecoverable_error_message_ = message; 938 unrecoverable_error_location_ = from_here; 939 940 UMA_HISTOGRAM_ENUMERATION(kSyncUnrecoverableErrorHistogram, 941 unrecoverable_error_reason_, 942 ERROR_REASON_LIMIT); 943 NotifyObservers(); 944 std::string location; 945 from_here.Write(true, true, &location); 946 LOG(ERROR) 947 << "Unrecoverable error detected at " << location 948 << " -- ProfileSyncService unusable: " << message; 949 950 // Shut all data types down. 951 base::MessageLoop::current()->PostTask(FROM_HERE, 952 base::Bind(&ProfileSyncService::ShutdownImpl, 953 weak_factory_.GetWeakPtr(), 954 delete_sync_database ? 955 browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD : 956 browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD)); 957} 958 959// TODO(zea): Move this logic into the DataTypeController/DataTypeManager. 960void ProfileSyncService::DisableDatatype( 961 syncer::ModelType type, 962 const tracked_objects::Location& from_here, 963 std::string message) { 964 // First deactivate the type so that no further server changes are 965 // passed onto the change processor. 966 DeactivateDataType(type); 967 968 syncer::SyncError error(from_here, 969 syncer::SyncError::DATATYPE_ERROR, 970 message, 971 type); 972 973 std::map<syncer::ModelType, syncer::SyncError> errors; 974 errors[type] = error; 975 976 // Update this before posting a task. So if a configure happens before 977 // the task that we are going to post, this type would still be disabled. 978 failed_data_types_handler_.UpdateFailedDataTypes(errors); 979 980 base::MessageLoop::current()->PostTask(FROM_HERE, 981 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager, 982 weak_factory_.GetWeakPtr())); 983} 984 985void ProfileSyncService::ReenableDatatype(syncer::ModelType type) { 986 // Only reconfigure if the type actually had a data type or unready error. 987 if (!failed_data_types_handler_.ResetDataTypeErrorFor(type) && 988 !failed_data_types_handler_.ResetUnreadyErrorFor(type)) { 989 return; 990 } 991 992 // If the type is no longer enabled, don't bother reconfiguring. 993 // TODO(zea): something else should encapsulate the notion of "whether a type 994 // should be enabled". 995 if (!syncer::CoreTypes().Has(type) && !GetPreferredDataTypes().Has(type)) 996 return; 997 998 base::MessageLoop::current()->PostTask(FROM_HERE, 999 base::Bind(&ProfileSyncService::ReconfigureDatatypeManager, 1000 weak_factory_.GetWeakPtr())); 1001} 1002 1003void ProfileSyncService::UpdateBackendInitUMA(bool success) { 1004 if (backend_mode_ != SYNC) 1005 return; 1006 1007 is_first_time_sync_configure_ = !HasSyncSetupCompleted(); 1008 1009 if (is_first_time_sync_configure_) { 1010 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeFirstTimeSuccess", success); 1011 } else { 1012 UMA_HISTOGRAM_BOOLEAN("Sync.BackendInitializeRestoreSuccess", success); 1013 } 1014 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); 1022 } 1023} 1024 1025void ProfileSyncService::PostBackendInitialization() { 1026 // Never get here for backup / restore. 1027 DCHECK_EQ(backend_mode_, SYNC); 1028 1029 if (last_backup_time_) { 1030 browser_sync::SyncedDeviceTracker* device_tracker = 1031 backend_->GetSyncedDeviceTracker(); 1032 if (device_tracker) 1033 device_tracker->UpdateLocalDeviceBackupTime(*last_backup_time_); 1034 } 1035 1036 if (protocol_event_observers_.might_have_observers()) { 1037 backend_->RequestBufferedProtocolEventsAndEnableForwarding(); 1038 } 1039 1040 non_blocking_data_type_manager_.ConnectSyncBackend( 1041 backend_->GetSyncContextProxy()); 1042 1043 if (type_debug_info_observers_.might_have_observers()) { 1044 backend_->EnableDirectoryTypeDebugInfoForwarding(); 1045 } 1046 1047 // If we have a cached passphrase use it to decrypt/encrypt data now that the 1048 // backend is initialized. We want to call this before notifying observers in 1049 // case this operation affects the "passphrase required" status. 1050 ConsumeCachedPassphraseIfPossible(); 1051 1052 // The very first time the backend initializes is effectively the first time 1053 // we can say we successfully "synced". last_synced_time_ will only be null 1054 // in this case, because the pref wasn't restored on StartUp. 1055 if (last_synced_time_.is_null()) { 1056 UpdateLastSyncedTime(); 1057 } 1058 1059 if (startup_controller_.auto_start_enabled() && !FirstSetupInProgress()) { 1060 // Backend is initialized but we're not in sync setup, so this must be an 1061 // autostart - mark our sync setup as completed and we'll start syncing 1062 // below. 1063 SetSyncSetupCompleted(); 1064 } 1065 1066 // Check HasSyncSetupCompleted() before NotifyObservers() to avoid spurious 1067 // data type configuration because observer may flag setup as complete and 1068 // trigger data type configuration. 1069 if (HasSyncSetupCompleted()) { 1070 ConfigureDataTypeManager(); 1071 } else { 1072 DCHECK(FirstSetupInProgress()); 1073 } 1074 1075 NotifyObservers(); 1076} 1077 1078void ProfileSyncService::OnBackendInitialized( 1079 const syncer::WeakHandle<syncer::JsBackend>& js_backend, 1080 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>& 1081 debug_info_listener, 1082 bool success) { 1083 UpdateBackendInitUMA(success); 1084 1085 if (!success) { 1086 // Something went unexpectedly wrong. Play it safe: stop syncing at once 1087 // and surface error UI to alert the user sync has stopped. 1088 // Keep the directory around for now so that on restart we will retry 1089 // again and potentially succeed in presence of transient file IO failures 1090 // or permissions issues, etc. 1091 // 1092 // TODO(rlarocque): Consider making this UnrecoverableError less special. 1093 // Unlike every other UnrecoverableError, it does not delete our sync data. 1094 // This exception made sense at the time it was implemented, but our new 1095 // directory corruption recovery mechanism makes it obsolete. By the time 1096 // we get here, we will have already tried and failed to delete the 1097 // directory. It would be no big deal if we tried to delete it again. 1098 OnInternalUnrecoverableError(FROM_HERE, 1099 "BackendInitialize failure", 1100 false, 1101 ERROR_REASON_BACKEND_INIT_FAILURE); 1102 return; 1103 } 1104 1105 backend_initialized_ = true; 1106 1107 sync_js_controller_.AttachJsBackend(js_backend); 1108 debug_info_listener_ = debug_info_listener; 1109 1110 // Give the DataTypeControllers a handle to the now initialized backend 1111 // as a UserShare. 1112 for (DataTypeController::TypeMap::iterator it = 1113 directory_data_type_controllers_.begin(); 1114 it != directory_data_type_controllers_.end(); ++it) { 1115 it->second->OnUserShareReady(GetUserShare()); 1116 } 1117 1118 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) 1119 ConfigureDataTypeManager(); 1120 else 1121 PostBackendInitialization(); 1122} 1123 1124void ProfileSyncService::OnSyncCycleCompleted() { 1125 UpdateLastSyncedTime(); 1126 if (IsSessionsDataTypeControllerRunning()) { 1127 // Trigger garbage collection of old sessions now that we've downloaded 1128 // any new session data. 1129 base::MessageLoop::current()->PostTask(FROM_HERE, base::Bind( 1130 &browser_sync::SessionsSyncManager::DoGarbageCollection, 1131 base::AsWeakPtr(sessions_sync_manager_.get()))); 1132 } 1133 DVLOG(2) << "Notifying observers sync cycle completed"; 1134 NotifySyncCycleCompleted(); 1135} 1136 1137void ProfileSyncService::OnExperimentsChanged( 1138 const syncer::Experiments& experiments) { 1139 if (current_experiments_.Matches(experiments)) 1140 return; 1141 1142 current_experiments_ = experiments; 1143 1144 // Handle preference-backed experiments first. 1145 if (experiments.gcm_channel_state == syncer::Experiments::SUPPRESSED) { 1146 profile()->GetPrefs()->SetBoolean(prefs::kGCMChannelEnabled, false); 1147 gcm::GCMProfileServiceFactory::GetForProfile(profile())->driver() 1148 ->Disable(); 1149 } else { 1150 profile()->GetPrefs()->ClearPref(prefs::kGCMChannelEnabled); 1151 gcm::GCMProfileServiceFactory::GetForProfile(profile())->driver() 1152 ->Enable(); 1153 } 1154 1155 profile()->GetPrefs()->SetBoolean(prefs::kInvalidationServiceUseGCMChannel, 1156 experiments.gcm_invalidations_enabled); 1157 1158 if (experiments.enhanced_bookmarks_enabled) { 1159 profile_->GetPrefs()->SetString( 1160 sync_driver::prefs::kEnhancedBookmarksExtensionId, 1161 experiments.enhanced_bookmarks_ext_id); 1162 } else { 1163 profile_->GetPrefs()->ClearPref( 1164 sync_driver::prefs::kEnhancedBookmarksExtensionId); 1165 } 1166 UpdateBookmarksExperimentState( 1167 profile_->GetPrefs(), g_browser_process->local_state(), true, 1168 experiments.enhanced_bookmarks_enabled ? BOOKMARKS_EXPERIMENT_ENABLED : 1169 BOOKMARKS_EXPERIMENT_NONE); 1170 1171 // If this is a first time sync for a client, this will be called before 1172 // OnBackendInitialized() to ensure the new datatypes are available at sync 1173 // setup. As a result, the migrator won't exist yet. This is fine because for 1174 // first time sync cases we're only concerned with making the datatype 1175 // available. 1176 if (migrator_.get() && 1177 migrator_->state() != browser_sync::BackendMigrator::IDLE) { 1178 DVLOG(1) << "Dropping OnExperimentsChanged due to migrator busy."; 1179 return; 1180 } 1181 1182 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes(); 1183 syncer::ModelTypeSet to_add; 1184 const syncer::ModelTypeSet to_register = 1185 Difference(to_add, registered_types); 1186 DVLOG(2) << "OnExperimentsChanged called with types: " 1187 << syncer::ModelTypeSetToString(to_add); 1188 DVLOG(2) << "Enabling types: " << syncer::ModelTypeSetToString(to_register); 1189 1190 for (syncer::ModelTypeSet::Iterator it = to_register.First(); 1191 it.Good(); it.Inc()) { 1192 // Received notice to enable experimental type. Check if the type is 1193 // registered, and if not register a new datatype controller. 1194 RegisterNewDataType(it.Get()); 1195 } 1196 1197 // Check if the user has "Keep Everything Synced" enabled. If so, we want 1198 // to turn on all experimental types if they're not already on. Otherwise we 1199 // leave them off. 1200 // Note: if any types are already registered, we don't turn them on. This 1201 // covers the case where we're already in the process of reconfiguring 1202 // to turn an experimental type on. 1203 if (sync_prefs_.HasKeepEverythingSynced()) { 1204 // Mark all data types as preferred. 1205 sync_prefs_.SetPreferredDataTypes(registered_types, registered_types); 1206 1207 // Only automatically turn on types if we have already finished set up. 1208 // Otherwise, just leave the experimental types on by default. 1209 if (!to_register.Empty() && HasSyncSetupCompleted() && migrator_) { 1210 DVLOG(1) << "Dynamically enabling new datatypes: " 1211 << syncer::ModelTypeSetToString(to_register); 1212 OnMigrationNeededForTypes(to_register); 1213 } 1214 } 1215} 1216 1217void ProfileSyncService::UpdateAuthErrorState(const AuthError& error) { 1218 is_auth_in_progress_ = false; 1219 last_auth_error_ = error; 1220 1221 NotifyObservers(); 1222} 1223 1224namespace { 1225 1226AuthError ConnectionStatusToAuthError( 1227 syncer::ConnectionStatus status) { 1228 switch (status) { 1229 case syncer::CONNECTION_OK: 1230 return AuthError::AuthErrorNone(); 1231 break; 1232 case syncer::CONNECTION_AUTH_ERROR: 1233 return AuthError(AuthError::INVALID_GAIA_CREDENTIALS); 1234 break; 1235 case syncer::CONNECTION_SERVER_ERROR: 1236 return AuthError(AuthError::CONNECTION_FAILED); 1237 break; 1238 default: 1239 NOTREACHED(); 1240 return AuthError(AuthError::CONNECTION_FAILED); 1241 } 1242} 1243 1244} // namespace 1245 1246void ProfileSyncService::OnConnectionStatusChange( 1247 syncer::ConnectionStatus status) { 1248 connection_status_update_time_ = base::Time::Now(); 1249 connection_status_ = status; 1250 if (status == syncer::CONNECTION_AUTH_ERROR) { 1251 // Sync server returned error indicating that access token is invalid. It 1252 // could be either expired or access is revoked. Let's request another 1253 // access token and if access is revoked then request for token will fail 1254 // with corresponding error. If access token is repeatedly reported 1255 // invalid, there may be some issues with server, e.g. authentication 1256 // state is inconsistent on sync and token server. In that case, we 1257 // backoff token requests exponentially to avoid hammering token server 1258 // too much and to avoid getting same token due to token server's caching 1259 // policy. |request_access_token_retry_timer_| is used to backoff request 1260 // triggered by both auth error and failure talking to GAIA server. 1261 // Therefore, we're likely to reach the backoff ceiling more quickly than 1262 // you would expect from looking at the BackoffPolicy if both types of 1263 // errors happen. We shouldn't receive two errors back-to-back without 1264 // attempting a token/sync request in between, thus crank up request delay 1265 // unnecessary. This is because we won't make a sync request if we hit an 1266 // error until GAIA succeeds at sending a new token, and we won't request 1267 // a new token unless sync reports a token failure. But to be safe, don't 1268 // schedule request if this happens. 1269 if (request_access_token_retry_timer_.IsRunning()) { 1270 NOTREACHED(); 1271 } else if (request_access_token_backoff_.failure_count() == 0) { 1272 // First time request without delay. Currently invalid token is used 1273 // to initialize sync backend and we'll always end up here. We don't 1274 // want to delay initialization. 1275 request_access_token_backoff_.InformOfRequest(false); 1276 RequestAccessToken(); 1277 } else { 1278 request_access_token_backoff_.InformOfRequest(false); 1279 request_access_token_retry_timer_.Start( 1280 FROM_HERE, 1281 request_access_token_backoff_.GetTimeUntilRelease(), 1282 base::Bind(&ProfileSyncService::RequestAccessToken, 1283 weak_factory_.GetWeakPtr())); 1284 } 1285 } else { 1286 // Reset backoff time after successful connection. 1287 if (status == syncer::CONNECTION_OK) { 1288 // Request shouldn't be scheduled at this time. But if it is, it's 1289 // possible that sync flips between OK and auth error states rapidly, 1290 // thus hammers token server. To be safe, only reset backoff delay when 1291 // no scheduled request. 1292 if (request_access_token_retry_timer_.IsRunning()) { 1293 NOTREACHED(); 1294 } else { 1295 request_access_token_backoff_.Reset(); 1296 } 1297 } 1298 1299 const GoogleServiceAuthError auth_error = 1300 ConnectionStatusToAuthError(status); 1301 DVLOG(1) << "Connection status change: " << auth_error.ToString(); 1302 UpdateAuthErrorState(auth_error); 1303 } 1304} 1305 1306void ProfileSyncService::StopSyncingPermanently() { 1307 sync_prefs_.SetStartSuppressed(true); 1308 DisableForUser(); 1309} 1310 1311void ProfileSyncService::OnPassphraseRequired( 1312 syncer::PassphraseRequiredReason reason, 1313 const sync_pb::EncryptedData& pending_keys) { 1314 DCHECK(backend_.get()); 1315 DCHECK(backend_->IsNigoriEnabled()); 1316 1317 // TODO(lipalani) : add this check to other locations as well. 1318 if (HasUnrecoverableError()) { 1319 // When unrecoverable error is detected we post a task to shutdown the 1320 // backend. The task might not have executed yet. 1321 return; 1322 } 1323 1324 DVLOG(1) << "Passphrase required with reason: " 1325 << syncer::PassphraseRequiredReasonToString(reason); 1326 passphrase_required_reason_ = reason; 1327 1328 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes(); 1329 if (directory_data_type_manager_) { 1330 // Reconfigure without the encrypted types (excluded implicitly via the 1331 // failed datatypes handler). 1332 directory_data_type_manager_->Configure(types, 1333 syncer::CONFIGURE_REASON_CRYPTO); 1334 } 1335 1336 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005. 1337 1338 // Notify observers that the passphrase status may have changed. 1339 NotifyObservers(); 1340} 1341 1342void ProfileSyncService::OnPassphraseAccepted() { 1343 DVLOG(1) << "Received OnPassphraseAccepted."; 1344 1345 // If the pending keys were resolved via keystore, it's possible we never 1346 // consumed our cached passphrase. Clear it now. 1347 if (!cached_passphrase_.empty()) 1348 cached_passphrase_.clear(); 1349 1350 // Reset passphrase_required_reason_ since we know we no longer require the 1351 // passphrase. We do this here rather than down in ResolvePassphraseRequired() 1352 // because that can be called by OnPassphraseRequired() if no encrypted data 1353 // types are enabled, and we don't want to clobber the true passphrase error. 1354 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED; 1355 1356 // Make sure the data types that depend on the passphrase are started at 1357 // this time. 1358 const syncer::ModelTypeSet types = GetPreferredDirectoryDataTypes(); 1359 if (directory_data_type_manager_) { 1360 // Re-enable any encrypted types if necessary. 1361 directory_data_type_manager_->Configure(types, 1362 syncer::CONFIGURE_REASON_CRYPTO); 1363 } 1364 1365 // TODO(rlarocque): Support non-blocking types. http://crbug.com/351005. 1366 1367 NotifyObservers(); 1368} 1369 1370void ProfileSyncService::OnEncryptedTypesChanged( 1371 syncer::ModelTypeSet encrypted_types, 1372 bool encrypt_everything) { 1373 encrypted_types_ = encrypted_types; 1374 encrypt_everything_ = encrypt_everything; 1375 DVLOG(1) << "Encrypted types changed to " 1376 << syncer::ModelTypeSetToString(encrypted_types_) 1377 << " (encrypt everything is set to " 1378 << (encrypt_everything_ ? "true" : "false") << ")"; 1379 DCHECK(encrypted_types_.Has(syncer::PASSWORDS)); 1380 1381 // If sessions are encrypted, full history sync is not possible, and 1382 // delete directives are unnecessary. 1383 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES) && 1384 encrypted_types_.Has(syncer::SESSIONS)) { 1385 DisableDatatype(syncer::HISTORY_DELETE_DIRECTIVES, 1386 FROM_HERE, 1387 "Delete directives not supported with encryption."); 1388 } 1389} 1390 1391void ProfileSyncService::OnEncryptionComplete() { 1392 DVLOG(1) << "Encryption complete"; 1393 if (encryption_pending_ && encrypt_everything_) { 1394 encryption_pending_ = false; 1395 // This is to nudge the integration tests when encryption is 1396 // finished. 1397 NotifyObservers(); 1398 } 1399} 1400 1401void ProfileSyncService::OnMigrationNeededForTypes( 1402 syncer::ModelTypeSet types) { 1403 DCHECK(backend_initialized_); 1404 DCHECK(directory_data_type_manager_.get()); 1405 1406 // Migrator must be valid, because we don't sync until it is created and this 1407 // callback originates from a sync cycle. 1408 migrator_->MigrateTypes(types); 1409} 1410 1411void ProfileSyncService::OnActionableError(const SyncProtocolError& error) { 1412 last_actionable_error_ = error; 1413 DCHECK_NE(last_actionable_error_.action, 1414 syncer::UNKNOWN_ACTION); 1415 switch (error.action) { 1416 case syncer::UPGRADE_CLIENT: 1417 case syncer::CLEAR_USER_DATA_AND_RESYNC: 1418 case syncer::ENABLE_SYNC_ON_ACCOUNT: 1419 case syncer::STOP_AND_RESTART_SYNC: 1420 // TODO(lipalani) : if setup in progress we want to display these 1421 // actions in the popup. The current experience might not be optimal for 1422 // the user. We just dismiss the dialog. 1423 if (startup_controller_.setup_in_progress()) { 1424 StopSyncingPermanently(); 1425 expect_sync_configuration_aborted_ = true; 1426 } 1427 // Trigger an unrecoverable error to stop syncing. 1428 OnInternalUnrecoverableError(FROM_HERE, 1429 last_actionable_error_.error_description, 1430 true, 1431 ERROR_REASON_ACTIONABLE_ERROR); 1432 break; 1433 case syncer::DISABLE_SYNC_AND_ROLLBACK: 1434 backup_rollback_controller_.OnRollbackReceived(); 1435 // Fall through to shutdown backend and sign user out. 1436 case syncer::DISABLE_SYNC_ON_CLIENT: 1437 StopSyncingPermanently(); 1438#if !defined(OS_CHROMEOS) 1439 // On desktop Chrome, sign out the user after a dashboard clear. 1440 // Skip sign out on ChromeOS/Android. 1441 if (!startup_controller_.auto_start_enabled()) { 1442 SigninManagerFactory::GetForProfile(profile_)->SignOut( 1443 signin_metrics::SERVER_FORCED_DISABLE); 1444 } 1445#endif 1446 break; 1447 case syncer::ROLLBACK_DONE: 1448 backup_rollback_controller_.OnRollbackDone(); 1449 break; 1450 case syncer::STOP_SYNC_FOR_DISABLED_ACCOUNT: 1451 // Sync disabled by domain admin. we should stop syncing until next 1452 // restart. 1453 sync_disabled_by_admin_ = true; 1454 ShutdownImpl(browser_sync::SyncBackendHost::DISABLE_AND_CLAIM_THREAD); 1455 break; 1456 default: 1457 NOTREACHED(); 1458 } 1459 NotifyObservers(); 1460 1461 backup_rollback_controller_.Start(base::TimeDelta()); 1462} 1463 1464void ProfileSyncService::OnConfigureDone( 1465 const browser_sync::DataTypeManager::ConfigureResult& result) { 1466 // We should have cleared our cached passphrase before we get here (in 1467 // OnBackendInitialized()). 1468 DCHECK(cached_passphrase_.empty()); 1469 1470 configure_status_ = result.status; 1471 1472 if (backend_mode_ != SYNC) { 1473 if (configure_status_ == DataTypeManager::OK || 1474 configure_status_ == DataTypeManager::PARTIAL_SUCCESS) { 1475 StartSyncingWithServer(); 1476 } else if (!expect_sync_configuration_aborted_) { 1477 DVLOG(1) << "Backup/rollback backend failed to configure."; 1478 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD); 1479 } 1480 1481 return; 1482 } 1483 1484 if (!sync_configure_start_time_.is_null()) { 1485 if (result.status == DataTypeManager::OK || 1486 result.status == DataTypeManager::PARTIAL_SUCCESS) { 1487 base::Time sync_configure_stop_time = base::Time::Now(); 1488 base::TimeDelta delta = sync_configure_stop_time - 1489 sync_configure_start_time_; 1490 if (is_first_time_sync_configure_) { 1491 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceInitialConfigureTime", delta); 1492 } else { 1493 UMA_HISTOGRAM_LONG_TIMES("Sync.ServiceSubsequentConfigureTime", 1494 delta); 1495 } 1496 } 1497 sync_configure_start_time_ = base::Time(); 1498 } 1499 1500 // Notify listeners that configuration is done. 1501 content::NotificationService::current()->Notify( 1502 chrome::NOTIFICATION_SYNC_CONFIGURE_DONE, 1503 content::Source<ProfileSyncService>(this), 1504 content::NotificationService::NoDetails()); 1505 1506 DVLOG(1) << "PSS OnConfigureDone called with status: " << configure_status_; 1507 // The possible status values: 1508 // ABORT - Configuration was aborted. This is not an error, if 1509 // initiated by user. 1510 // OK - Everything succeeded. 1511 // PARTIAL_SUCCESS - Some datatypes failed to start. 1512 // Everything else is an UnrecoverableError. So treat it as such. 1513 1514 // First handle the abort case. 1515 if (configure_status_ == DataTypeManager::ABORTED && 1516 expect_sync_configuration_aborted_) { 1517 DVLOG(0) << "ProfileSyncService::Observe Sync Configure aborted"; 1518 expect_sync_configuration_aborted_ = false; 1519 return; 1520 } 1521 1522 // Handle unrecoverable error. 1523 if (configure_status_ != DataTypeManager::OK && 1524 configure_status_ != DataTypeManager::PARTIAL_SUCCESS) { 1525 // Something catastrophic had happened. We should only have one 1526 // error representing it. 1527 DCHECK_EQ(result.failed_data_types.size(), 1528 static_cast<unsigned int>(1)); 1529 syncer::SyncError error = result.failed_data_types.begin()->second; 1530 DCHECK(error.IsSet()); 1531 std::string message = 1532 "Sync configuration failed with status " + 1533 DataTypeManager::ConfigureStatusToString(configure_status_) + 1534 " during " + syncer::ModelTypeToString(error.model_type()) + 1535 ": " + error.message(); 1536 LOG(ERROR) << "ProfileSyncService error: " << message; 1537 OnInternalUnrecoverableError(error.location(), 1538 message, 1539 true, 1540 ERROR_REASON_CONFIGURATION_FAILURE); 1541 return; 1542 } 1543 1544 // We should never get in a state where we have no encrypted datatypes 1545 // enabled, and yet we still think we require a passphrase for decryption. 1546 DCHECK(!(IsPassphraseRequiredForDecryption() && 1547 !IsEncryptedDatatypeEnabled())); 1548 1549 // This must be done before we start syncing with the server to avoid 1550 // sending unencrypted data up on a first time sync. 1551 if (encryption_pending_) 1552 backend_->EnableEncryptEverything(); 1553 NotifyObservers(); 1554 1555 if (migrator_.get() && 1556 migrator_->state() != browser_sync::BackendMigrator::IDLE) { 1557 // Migration in progress. Let the migrator know we just finished 1558 // configuring something. It will be up to the migrator to call 1559 // StartSyncingWithServer() if migration is now finished. 1560 migrator_->OnConfigureDone(result); 1561 } else { 1562 StartSyncingWithServer(); 1563 } 1564} 1565 1566void ProfileSyncService::OnConfigureRetry() { 1567 // We should have cleared our cached passphrase before we get here (in 1568 // OnBackendInitialized()). 1569 DCHECK(cached_passphrase_.empty()); 1570 1571 OnSyncConfigureRetry(); 1572} 1573 1574void ProfileSyncService::OnConfigureStart() { 1575 sync_configure_start_time_ = base::Time::Now(); 1576 NotifyObservers(); 1577} 1578 1579ProfileSyncService::SyncStatusSummary 1580 ProfileSyncService::QuerySyncStatusSummary() { 1581 if (HasUnrecoverableError()) { 1582 return UNRECOVERABLE_ERROR; 1583 } else if (!backend_) { 1584 return NOT_ENABLED; 1585 } else if (backend_mode_ == BACKUP) { 1586 return BACKUP_USER_DATA; 1587 } else if (backend_mode_ == ROLLBACK) { 1588 return ROLLBACK_USER_DATA; 1589 } else if (backend_.get() && !HasSyncSetupCompleted()) { 1590 return SETUP_INCOMPLETE; 1591 } else if ( 1592 backend_.get() && HasSyncSetupCompleted() && 1593 directory_data_type_manager_.get() && 1594 directory_data_type_manager_->state() != DataTypeManager::CONFIGURED) { 1595 return DATATYPES_NOT_INITIALIZED; 1596 } else if (ShouldPushChanges()) { 1597 return INITIALIZED; 1598 } 1599 return UNKNOWN_ERROR; 1600} 1601 1602std::string ProfileSyncService::QuerySyncStatusSummaryString() { 1603 SyncStatusSummary status = QuerySyncStatusSummary(); 1604 1605 std::string config_status_str = 1606 configure_status_ != DataTypeManager::UNKNOWN ? 1607 DataTypeManager::ConfigureStatusToString(configure_status_) : ""; 1608 1609 switch (status) { 1610 case UNRECOVERABLE_ERROR: 1611 return "Unrecoverable error detected"; 1612 case NOT_ENABLED: 1613 return "Syncing not enabled"; 1614 case SETUP_INCOMPLETE: 1615 return "First time sync setup incomplete"; 1616 case DATATYPES_NOT_INITIALIZED: 1617 return "Datatypes not fully initialized"; 1618 case INITIALIZED: 1619 return "Sync service initialized"; 1620 case BACKUP_USER_DATA: 1621 return "Backing-up user data. Status: " + config_status_str; 1622 case ROLLBACK_USER_DATA: 1623 return "Restoring user data. Status: " + config_status_str; 1624 default: 1625 return "Status unknown: Internal error?"; 1626 } 1627} 1628 1629std::string ProfileSyncService::GetBackendInitializationStateString() const { 1630 return startup_controller_.GetBackendInitializationStateString(); 1631} 1632 1633bool ProfileSyncService::auto_start_enabled() const { 1634 return startup_controller_.auto_start_enabled(); 1635} 1636 1637bool ProfileSyncService::setup_in_progress() const { 1638 return startup_controller_.setup_in_progress(); 1639} 1640 1641bool ProfileSyncService::QueryDetailedSyncStatus( 1642 SyncBackendHost::Status* result) { 1643 if (backend_.get() && backend_initialized_) { 1644 *result = backend_->GetDetailedStatus(); 1645 return true; 1646 } else { 1647 SyncBackendHost::Status status; 1648 status.sync_protocol_error = last_actionable_error_; 1649 *result = status; 1650 return false; 1651 } 1652} 1653 1654const AuthError& ProfileSyncService::GetAuthError() const { 1655 return last_auth_error_; 1656} 1657 1658bool ProfileSyncService::FirstSetupInProgress() const { 1659 return !HasSyncSetupCompleted() && startup_controller_.setup_in_progress(); 1660} 1661 1662void ProfileSyncService::SetSetupInProgress(bool setup_in_progress) { 1663 // This method is a no-op if |setup_in_progress_| remains unchanged. 1664 if (startup_controller_.setup_in_progress() == setup_in_progress) 1665 return; 1666 1667 startup_controller_.set_setup_in_progress(setup_in_progress); 1668 if (!setup_in_progress && sync_initialized()) 1669 ReconfigureDatatypeManager(); 1670 NotifyObservers(); 1671} 1672 1673bool ProfileSyncService::sync_initialized() const { 1674 return backend_initialized_; 1675} 1676 1677bool ProfileSyncService::waiting_for_auth() const { 1678 return is_auth_in_progress_; 1679} 1680 1681const syncer::Experiments& ProfileSyncService::current_experiments() const { 1682 return current_experiments_; 1683} 1684 1685bool ProfileSyncService::HasUnrecoverableError() const { 1686 return unrecoverable_error_reason_ != ERROR_REASON_UNSET; 1687} 1688 1689bool ProfileSyncService::IsPassphraseRequired() const { 1690 return passphrase_required_reason_ != 1691 syncer::REASON_PASSPHRASE_NOT_REQUIRED; 1692} 1693 1694bool ProfileSyncService::IsPassphraseRequiredForDecryption() const { 1695 // If there is an encrypted datatype enabled and we don't have the proper 1696 // passphrase, we must prompt the user for a passphrase. The only way for the 1697 // user to avoid entering their passphrase is to disable the encrypted types. 1698 return IsEncryptedDatatypeEnabled() && IsPassphraseRequired(); 1699} 1700 1701base::string16 ProfileSyncService::GetLastSyncedTimeString() const { 1702 if (last_synced_time_.is_null()) 1703 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER); 1704 1705 base::TimeDelta last_synced = base::Time::Now() - last_synced_time_; 1706 1707 if (last_synced < base::TimeDelta::FromMinutes(1)) 1708 return l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW); 1709 1710 return ui::TimeFormat::Simple(ui::TimeFormat::FORMAT_ELAPSED, 1711 ui::TimeFormat::LENGTH_SHORT, last_synced); 1712} 1713 1714void ProfileSyncService::UpdateSelectedTypesHistogram( 1715 bool sync_everything, const syncer::ModelTypeSet chosen_types) const { 1716 if (!HasSyncSetupCompleted() || 1717 sync_everything != sync_prefs_.HasKeepEverythingSynced()) { 1718 UMA_HISTOGRAM_BOOLEAN("Sync.SyncEverything", sync_everything); 1719 } 1720 1721 // Only log the data types that are shown in the sync settings ui. 1722 // Note: the order of these types must match the ordering of 1723 // the respective types in ModelType 1724const browser_sync::user_selectable_type::UserSelectableSyncType 1725 user_selectable_types[] = { 1726 browser_sync::user_selectable_type::BOOKMARKS, 1727 browser_sync::user_selectable_type::PREFERENCES, 1728 browser_sync::user_selectable_type::PASSWORDS, 1729 browser_sync::user_selectable_type::AUTOFILL, 1730 browser_sync::user_selectable_type::THEMES, 1731 browser_sync::user_selectable_type::TYPED_URLS, 1732 browser_sync::user_selectable_type::EXTENSIONS, 1733 browser_sync::user_selectable_type::APPS, 1734 browser_sync::user_selectable_type::PROXY_TABS 1735 }; 1736 1737 COMPILE_ASSERT(32 == syncer::MODEL_TYPE_COUNT, UpdateCustomConfigHistogram); 1738 1739 if (!sync_everything) { 1740 const syncer::ModelTypeSet current_types = GetPreferredDataTypes(); 1741 1742 syncer::ModelTypeSet type_set = syncer::UserSelectableTypes(); 1743 syncer::ModelTypeSet::Iterator it = type_set.First(); 1744 1745 DCHECK_EQ(arraysize(user_selectable_types), type_set.Size()); 1746 1747 for (size_t i = 0; i < arraysize(user_selectable_types) && it.Good(); 1748 ++i, it.Inc()) { 1749 const syncer::ModelType type = it.Get(); 1750 if (chosen_types.Has(type) && 1751 (!HasSyncSetupCompleted() || !current_types.Has(type))) { 1752 // Selected type has changed - log it. 1753 UMA_HISTOGRAM_ENUMERATION( 1754 "Sync.CustomSync", 1755 user_selectable_types[i], 1756 browser_sync::user_selectable_type::SELECTABLE_DATATYPE_COUNT + 1); 1757 } 1758 } 1759 } 1760} 1761 1762#if defined(OS_CHROMEOS) 1763void ProfileSyncService::RefreshSpareBootstrapToken( 1764 const std::string& passphrase) { 1765 browser_sync::SystemEncryptor encryptor; 1766 syncer::Cryptographer temp_cryptographer(&encryptor); 1767 // The first 2 params (hostname and username) doesn't have any effect here. 1768 syncer::KeyParams key_params = {"localhost", "dummy", passphrase}; 1769 1770 std::string bootstrap_token; 1771 if (!temp_cryptographer.AddKey(key_params)) { 1772 NOTREACHED() << "Failed to add key to cryptographer."; 1773 } 1774 temp_cryptographer.GetBootstrapToken(&bootstrap_token); 1775 sync_prefs_.SetSpareBootstrapToken(bootstrap_token); 1776} 1777#endif 1778 1779void ProfileSyncService::OnUserChoseDatatypes( 1780 bool sync_everything, 1781 syncer::ModelTypeSet chosen_types) { 1782 if (!backend_.get() && !HasUnrecoverableError()) { 1783 NOTREACHED(); 1784 return; 1785 } 1786 1787 UpdateSelectedTypesHistogram(sync_everything, chosen_types); 1788 sync_prefs_.SetKeepEverythingSynced(sync_everything); 1789 1790 failed_data_types_handler_.Reset(); 1791 if (GetActiveDataTypes().Has(syncer::HISTORY_DELETE_DIRECTIVES) && 1792 encrypted_types_.Has(syncer::SESSIONS)) { 1793 DisableDatatype(syncer::HISTORY_DELETE_DIRECTIVES, 1794 FROM_HERE, 1795 "Delete directives not supported with encryption."); 1796 } 1797 ChangePreferredDataTypes(chosen_types); 1798 AcknowledgeSyncedTypes(); 1799 NotifyObservers(); 1800} 1801 1802void ProfileSyncService::ChangePreferredDataTypes( 1803 syncer::ModelTypeSet preferred_types) { 1804 1805 DVLOG(1) << "ChangePreferredDataTypes invoked"; 1806 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes(); 1807 const syncer::ModelTypeSet registered_preferred_types = 1808 Intersection(registered_types, preferred_types); 1809 sync_prefs_.SetPreferredDataTypes(registered_types, 1810 registered_preferred_types); 1811 1812 // Now reconfigure the DTM. 1813 ReconfigureDatatypeManager(); 1814 1815 // TODO(rlarocque): Reconfigure the NonBlockingDataTypeManager, too. Blocked 1816 // on crbug.com/368834. Until that bug is fixed, it's difficult to tell 1817 // which types should be enabled and when. 1818} 1819 1820syncer::ModelTypeSet ProfileSyncService::GetActiveDataTypes() const { 1821 const syncer::ModelTypeSet preferred_types = GetPreferredDataTypes(); 1822 const syncer::ModelTypeSet failed_types = 1823 failed_data_types_handler_.GetFailedTypes(); 1824 return Difference(preferred_types, failed_types); 1825} 1826 1827syncer::ModelTypeSet ProfileSyncService::GetPreferredDataTypes() const { 1828 const syncer::ModelTypeSet registered_types = GetRegisteredDataTypes(); 1829 const syncer::ModelTypeSet preferred_types = 1830 sync_prefs_.GetPreferredDataTypes(registered_types); 1831 return preferred_types; 1832} 1833 1834syncer::ModelTypeSet 1835ProfileSyncService::GetPreferredDirectoryDataTypes() const { 1836 const syncer::ModelTypeSet registered_directory_types = 1837 GetRegisteredDirectoryDataTypes(); 1838 const syncer::ModelTypeSet preferred_types = 1839 sync_prefs_.GetPreferredDataTypes(registered_directory_types); 1840 return preferred_types; 1841} 1842 1843syncer::ModelTypeSet 1844ProfileSyncService::GetPreferredNonBlockingDataTypes() const { 1845 return sync_prefs_.GetPreferredDataTypes(GetRegisteredNonBlockingDataTypes()); 1846} 1847 1848syncer::ModelTypeSet ProfileSyncService::GetRegisteredDataTypes() const { 1849 return Union(GetRegisteredDirectoryDataTypes(), 1850 GetRegisteredNonBlockingDataTypes()); 1851} 1852 1853syncer::ModelTypeSet 1854ProfileSyncService::GetRegisteredDirectoryDataTypes() const { 1855 syncer::ModelTypeSet registered_types; 1856 // The directory_data_type_controllers_ are determined by command-line flags; 1857 // that's effectively what controls the values returned here. 1858 for (DataTypeController::TypeMap::const_iterator it = 1859 directory_data_type_controllers_.begin(); 1860 it != directory_data_type_controllers_.end(); ++it) { 1861 registered_types.Put(it->first); 1862 } 1863 return registered_types; 1864} 1865 1866syncer::ModelTypeSet 1867ProfileSyncService::GetRegisteredNonBlockingDataTypes() const { 1868 return non_blocking_data_type_manager_.GetRegisteredTypes(); 1869} 1870 1871bool ProfileSyncService::IsUsingSecondaryPassphrase() const { 1872 syncer::PassphraseType passphrase_type = GetPassphraseType(); 1873 return passphrase_type == syncer::FROZEN_IMPLICIT_PASSPHRASE || 1874 passphrase_type == syncer::CUSTOM_PASSPHRASE; 1875} 1876 1877syncer::PassphraseType ProfileSyncService::GetPassphraseType() const { 1878 return backend_->GetPassphraseType(); 1879} 1880 1881base::Time ProfileSyncService::GetExplicitPassphraseTime() const { 1882 return backend_->GetExplicitPassphraseTime(); 1883} 1884 1885bool ProfileSyncService::IsCryptographerReady( 1886 const syncer::BaseTransaction* trans) const { 1887 return backend_.get() && backend_->IsCryptographerReady(trans); 1888} 1889 1890void ProfileSyncService::ConfigurePriorityDataTypes() { 1891 const syncer::ModelTypeSet priority_types = 1892 Intersection(GetPreferredDirectoryDataTypes(), 1893 syncer::PriorityUserTypes()); 1894 if (!priority_types.Empty()) { 1895 const syncer::ConfigureReason reason = HasSyncSetupCompleted() ? 1896 syncer::CONFIGURE_REASON_RECONFIGURATION : 1897 syncer::CONFIGURE_REASON_NEW_CLIENT; 1898 directory_data_type_manager_->Configure(priority_types, reason); 1899 } 1900} 1901 1902void ProfileSyncService::ConfigureDataTypeManager() { 1903 // Don't configure datatypes if the setup UI is still on the screen - this 1904 // is to help multi-screen setting UIs (like iOS) where they don't want to 1905 // start syncing data until the user is done configuring encryption options, 1906 // etc. ReconfigureDatatypeManager() will get called again once the UI calls 1907 // SetSetupInProgress(false). 1908 if (startup_controller_.setup_in_progress()) 1909 return; 1910 1911 bool restart = false; 1912 if (!directory_data_type_manager_) { 1913 restart = true; 1914 directory_data_type_manager_.reset( 1915 factory_->CreateDataTypeManager(debug_info_listener_, 1916 &directory_data_type_controllers_, 1917 this, 1918 backend_.get(), 1919 this, 1920 &failed_data_types_handler_)); 1921 1922 // We create the migrator at the same time. 1923 migrator_.reset( 1924 new browser_sync::BackendMigrator( 1925 profile_->GetDebugName(), GetUserShare(), 1926 this, directory_data_type_manager_.get(), 1927 base::Bind(&ProfileSyncService::StartSyncingWithServer, 1928 base::Unretained(this)))); 1929 } 1930 1931 syncer::ModelTypeSet types; 1932 syncer::ConfigureReason reason = syncer::CONFIGURE_REASON_UNKNOWN; 1933 if (backend_mode_ == BACKUP || backend_mode_ == ROLLBACK) { 1934 types = syncer::BackupTypes(); 1935 reason = syncer::CONFIGURE_REASON_BACKUP_ROLLBACK; 1936 } else { 1937 types = GetPreferredDirectoryDataTypes(); 1938 if (!HasSyncSetupCompleted()) { 1939 reason = syncer::CONFIGURE_REASON_NEW_CLIENT; 1940 } else if (restart) { 1941 // Datatype downloads on restart are generally due to newly supported 1942 // datatypes (although it's also possible we're picking up where a failed 1943 // previous configuration left off). 1944 // TODO(sync): consider detecting configuration recovery and setting 1945 // the reason here appropriately. 1946 reason = syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE; 1947 } else { 1948 // The user initiated a reconfiguration (either to add or remove types). 1949 reason = syncer::CONFIGURE_REASON_RECONFIGURATION; 1950 } 1951 } 1952 1953 directory_data_type_manager_->Configure(types, reason); 1954} 1955 1956syncer::UserShare* ProfileSyncService::GetUserShare() const { 1957 if (backend_.get() && backend_initialized_) { 1958 return backend_->GetUserShare(); 1959 } 1960 NOTREACHED(); 1961 return NULL; 1962} 1963 1964syncer::sessions::SyncSessionSnapshot 1965ProfileSyncService::GetLastSessionSnapshot() const { 1966 if (HasSyncingBackend() && backend_initialized_) { 1967 return backend_->GetLastSessionSnapshot(); 1968 } 1969 return syncer::sessions::SyncSessionSnapshot(); 1970} 1971 1972bool ProfileSyncService::HasUnsyncedItems() const { 1973 if (HasSyncingBackend() && backend_initialized_) { 1974 return backend_->HasUnsyncedItems(); 1975 } 1976 NOTREACHED(); 1977 return false; 1978} 1979 1980browser_sync::BackendMigrator* 1981ProfileSyncService::GetBackendMigratorForTest() { 1982 return migrator_.get(); 1983} 1984 1985void ProfileSyncService::GetModelSafeRoutingInfo( 1986 syncer::ModelSafeRoutingInfo* out) const { 1987 if (backend_.get() && backend_initialized_) { 1988 backend_->GetModelSafeRoutingInfo(out); 1989 } else { 1990 NOTREACHED(); 1991 } 1992} 1993 1994base::Value* ProfileSyncService::GetTypeStatusMap() const { 1995 scoped_ptr<base::ListValue> result(new base::ListValue()); 1996 1997 if (!backend_.get() || !backend_initialized_) { 1998 return result.release(); 1999 } 2000 2001 FailedDataTypesHandler::TypeErrorMap error_map = 2002 failed_data_types_handler_.GetAllErrors(); 2003 2004 ModelTypeSet active_types; 2005 ModelTypeSet passive_types; 2006 ModelSafeRoutingInfo routing_info; 2007 backend_->GetModelSafeRoutingInfo(&routing_info); 2008 for (ModelSafeRoutingInfo::const_iterator it = routing_info.begin(); 2009 it != routing_info.end(); ++it) { 2010 if (it->second == syncer::GROUP_PASSIVE) { 2011 passive_types.Put(it->first); 2012 } else { 2013 active_types.Put(it->first); 2014 } 2015 } 2016 2017 SyncBackendHost::Status detailed_status = backend_->GetDetailedStatus(); 2018 ModelTypeSet &throttled_types(detailed_status.throttled_types); 2019 ModelTypeSet registered = GetRegisteredDataTypes(); 2020 scoped_ptr<base::DictionaryValue> type_status_header( 2021 new base::DictionaryValue()); 2022 2023 type_status_header->SetString("name", "Model Type"); 2024 type_status_header->SetString("status", "header"); 2025 type_status_header->SetString("value", "Group Type"); 2026 type_status_header->SetString("num_entries", "Total Entries"); 2027 type_status_header->SetString("num_live", "Live Entries"); 2028 result->Append(type_status_header.release()); 2029 2030 scoped_ptr<base::DictionaryValue> type_status; 2031 for (ModelTypeSet::Iterator it = registered.First(); it.Good(); it.Inc()) { 2032 ModelType type = it.Get(); 2033 2034 type_status.reset(new base::DictionaryValue()); 2035 type_status->SetString("name", ModelTypeToString(type)); 2036 2037 if (error_map.find(type) != error_map.end()) { 2038 const syncer::SyncError &error = error_map.find(type)->second; 2039 DCHECK(error.IsSet()); 2040 std::string error_text = "Error: " + error.location().ToString() + 2041 ", " + error.message(); 2042 type_status->SetString("status", "error"); 2043 type_status->SetString("value", error_text); 2044 } else if (syncer::IsProxyType(type) && passive_types.Has(type)) { 2045 // Show a proxy type in "ok" state unless it is disabled by user. 2046 DCHECK(!throttled_types.Has(type)); 2047 type_status->SetString("status", "ok"); 2048 type_status->SetString("value", "Passive"); 2049 } else if (throttled_types.Has(type) && passive_types.Has(type)) { 2050 type_status->SetString("status", "warning"); 2051 type_status->SetString("value", "Passive, Throttled"); 2052 } else if (passive_types.Has(type)) { 2053 type_status->SetString("status", "warning"); 2054 type_status->SetString("value", "Passive"); 2055 } else if (throttled_types.Has(type)) { 2056 type_status->SetString("status", "warning"); 2057 type_status->SetString("value", "Throttled"); 2058 } else if (GetRegisteredNonBlockingDataTypes().Has(type)) { 2059 type_status->SetString("status", "ok"); 2060 type_status->SetString("value", "Non-Blocking"); 2061 } else if (active_types.Has(type)) { 2062 type_status->SetString("status", "ok"); 2063 type_status->SetString("value", "Active: " + 2064 ModelSafeGroupToString(routing_info[type])); 2065 } else { 2066 type_status->SetString("status", "warning"); 2067 type_status->SetString("value", "Disabled by User"); 2068 } 2069 2070 int live_count = detailed_status.num_entries_by_type[type] - 2071 detailed_status.num_to_delete_entries_by_type[type]; 2072 type_status->SetInteger("num_entries", 2073 detailed_status.num_entries_by_type[type]); 2074 type_status->SetInteger("num_live", live_count); 2075 2076 result->Append(type_status.release()); 2077 } 2078 return result.release(); 2079} 2080 2081void ProfileSyncService::DeactivateDataType(syncer::ModelType type) { 2082 if (!backend_) 2083 return; 2084 backend_->DeactivateDataType(type); 2085} 2086 2087void ProfileSyncService::ConsumeCachedPassphraseIfPossible() { 2088 // If no cached passphrase, or sync backend hasn't started up yet, just exit. 2089 // If the backend isn't running yet, OnBackendInitialized() will call this 2090 // method again after the backend starts up. 2091 if (cached_passphrase_.empty() || !sync_initialized()) 2092 return; 2093 2094 // Backend is up and running, so we can consume the cached passphrase. 2095 std::string passphrase = cached_passphrase_; 2096 cached_passphrase_.clear(); 2097 2098 // If we need a passphrase to decrypt data, try the cached passphrase. 2099 if (passphrase_required_reason() == syncer::REASON_DECRYPTION) { 2100 if (SetDecryptionPassphrase(passphrase)) { 2101 DVLOG(1) << "Cached passphrase successfully decrypted pending keys"; 2102 return; 2103 } 2104 } 2105 2106 // If we get here, we don't have pending keys (or at least, the passphrase 2107 // doesn't decrypt them) - just try to re-encrypt using the encryption 2108 // passphrase. 2109 if (!IsUsingSecondaryPassphrase()) 2110 SetEncryptionPassphrase(passphrase, IMPLICIT); 2111} 2112 2113void ProfileSyncService::RequestAccessToken() { 2114 // Only one active request at a time. 2115 if (access_token_request_ != NULL) 2116 return; 2117 request_access_token_retry_timer_.Stop(); 2118 OAuth2TokenService::ScopeSet oauth2_scopes; 2119 oauth2_scopes.insert(signin_->GetSyncScopeToUse()); 2120 2121 // Invalidate previous token, otherwise token service will return the same 2122 // token again. 2123 const std::string& account_id = signin_->GetAccountIdToUse(); 2124 if (!access_token_.empty()) { 2125 oauth2_token_service_->InvalidateToken( 2126 account_id, oauth2_scopes, access_token_); 2127 } 2128 2129 access_token_.clear(); 2130 2131 token_request_time_ = base::Time::Now(); 2132 token_receive_time_ = base::Time(); 2133 next_token_request_time_ = base::Time(); 2134 access_token_request_ = 2135 oauth2_token_service_->StartRequest(account_id, oauth2_scopes, this); 2136} 2137 2138void ProfileSyncService::SetEncryptionPassphrase(const std::string& passphrase, 2139 PassphraseType type) { 2140 // This should only be called when the backend has been initialized. 2141 DCHECK(sync_initialized()); 2142 DCHECK(!(type == IMPLICIT && IsUsingSecondaryPassphrase())) << 2143 "Data is already encrypted using an explicit passphrase"; 2144 DCHECK(!(type == EXPLICIT && 2145 passphrase_required_reason_ == syncer::REASON_DECRYPTION)) << 2146 "Can not set explicit passphrase when decryption is needed."; 2147 2148 DVLOG(1) << "Setting " << (type == EXPLICIT ? "explicit" : "implicit") 2149 << " passphrase for encryption."; 2150 if (passphrase_required_reason_ == syncer::REASON_ENCRYPTION) { 2151 // REASON_ENCRYPTION implies that the cryptographer does not have pending 2152 // keys. Hence, as long as we're not trying to do an invalid passphrase 2153 // change (e.g. explicit -> explicit or explicit -> implicit), we know this 2154 // will succeed. If for some reason a new encryption key arrives via 2155 // sync later, the SBH will trigger another OnPassphraseRequired(). 2156 passphrase_required_reason_ = syncer::REASON_PASSPHRASE_NOT_REQUIRED; 2157 NotifyObservers(); 2158 } 2159 backend_->SetEncryptionPassphrase(passphrase, type == EXPLICIT); 2160} 2161 2162bool ProfileSyncService::SetDecryptionPassphrase( 2163 const std::string& passphrase) { 2164 if (IsPassphraseRequired()) { 2165 DVLOG(1) << "Setting passphrase for decryption."; 2166 return backend_->SetDecryptionPassphrase(passphrase); 2167 } else { 2168 NOTREACHED() << "SetDecryptionPassphrase must not be called when " 2169 "IsPassphraseRequired() is false."; 2170 return false; 2171 } 2172} 2173 2174void ProfileSyncService::EnableEncryptEverything() { 2175 // Tests override sync_initialized() to always return true, so we 2176 // must check that instead of |backend_initialized_|. 2177 // TODO(akalin): Fix the above. :/ 2178 DCHECK(sync_initialized()); 2179 // TODO(atwilson): Persist the encryption_pending_ flag to address the various 2180 // problems around cancelling encryption in the background (crbug.com/119649). 2181 if (!encrypt_everything_) 2182 encryption_pending_ = true; 2183} 2184 2185bool ProfileSyncService::encryption_pending() const { 2186 // We may be called during the setup process before we're 2187 // initialized (via IsEncryptedDatatypeEnabled and 2188 // IsPassphraseRequiredForDecryption). 2189 return encryption_pending_; 2190} 2191 2192bool ProfileSyncService::EncryptEverythingEnabled() const { 2193 DCHECK(backend_initialized_); 2194 return encrypt_everything_ || encryption_pending_; 2195} 2196 2197syncer::ModelTypeSet ProfileSyncService::GetEncryptedDataTypes() const { 2198 DCHECK(encrypted_types_.Has(syncer::PASSWORDS)); 2199 // We may be called during the setup process before we're 2200 // initialized. In this case, we default to the sensitive types. 2201 return encrypted_types_; 2202} 2203 2204void ProfileSyncService::OnSyncManagedPrefChange(bool is_sync_managed) { 2205 NotifyObservers(); 2206 if (is_sync_managed) { 2207 DisableForUser(); 2208 } else { 2209 // Sync is no longer disabled by policy. Try starting it up if appropriate. 2210 startup_controller_.TryStart(); 2211 } 2212} 2213 2214void ProfileSyncService::GoogleSigninSucceeded(const std::string& username, 2215 const std::string& password) { 2216 if (!sync_prefs_.IsStartSuppressed() && !password.empty()) { 2217 cached_passphrase_ = password; 2218 // Try to consume the passphrase we just cached. If the sync backend 2219 // is not running yet, the passphrase will remain cached until the 2220 // backend starts up. 2221 ConsumeCachedPassphraseIfPossible(); 2222 } 2223#if defined(OS_CHROMEOS) 2224 RefreshSpareBootstrapToken(password); 2225#endif 2226 if (!sync_initialized() || GetAuthError().state() != AuthError::NONE) { 2227 // Track the fact that we're still waiting for auth to complete. 2228 is_auth_in_progress_ = true; 2229 } 2230} 2231 2232void ProfileSyncService::GoogleSignedOut(const std::string& username) { 2233 sync_disabled_by_admin_ = false; 2234 DisableForUser(); 2235 2236 backup_rollback_controller_.Start(base::TimeDelta()); 2237} 2238 2239void ProfileSyncService::AddObserver( 2240 ProfileSyncServiceBase::Observer* observer) { 2241 observers_.AddObserver(observer); 2242} 2243 2244void ProfileSyncService::RemoveObserver( 2245 ProfileSyncServiceBase::Observer* observer) { 2246 observers_.RemoveObserver(observer); 2247} 2248 2249void ProfileSyncService::AddProtocolEventObserver( 2250 browser_sync::ProtocolEventObserver* observer) { 2251 protocol_event_observers_.AddObserver(observer); 2252 if (HasSyncingBackend()) { 2253 backend_->RequestBufferedProtocolEventsAndEnableForwarding(); 2254 } 2255} 2256 2257void ProfileSyncService::RemoveProtocolEventObserver( 2258 browser_sync::ProtocolEventObserver* observer) { 2259 protocol_event_observers_.RemoveObserver(observer); 2260 if (HasSyncingBackend() && 2261 !protocol_event_observers_.might_have_observers()) { 2262 backend_->DisableProtocolEventForwarding(); 2263 } 2264} 2265 2266void ProfileSyncService::AddTypeDebugInfoObserver( 2267 syncer::TypeDebugInfoObserver* type_debug_info_observer) { 2268 type_debug_info_observers_.AddObserver(type_debug_info_observer); 2269 if (type_debug_info_observers_.might_have_observers() && 2270 backend_initialized_) { 2271 backend_->EnableDirectoryTypeDebugInfoForwarding(); 2272 } 2273} 2274 2275void ProfileSyncService::RemoveTypeDebugInfoObserver( 2276 syncer::TypeDebugInfoObserver* type_debug_info_observer) { 2277 type_debug_info_observers_.RemoveObserver(type_debug_info_observer); 2278 if (!type_debug_info_observers_.might_have_observers() && 2279 backend_initialized_) { 2280 backend_->DisableDirectoryTypeDebugInfoForwarding(); 2281 } 2282} 2283 2284namespace { 2285 2286class GetAllNodesRequestHelper 2287 : public base::RefCountedThreadSafe<GetAllNodesRequestHelper> { 2288 public: 2289 GetAllNodesRequestHelper( 2290 syncer::ModelTypeSet requested_types, 2291 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback); 2292 2293 void OnReceivedNodesForTypes( 2294 const std::vector<syncer::ModelType>& types, 2295 ScopedVector<base::ListValue> scoped_node_lists); 2296 2297 private: 2298 friend class base::RefCountedThreadSafe<GetAllNodesRequestHelper>; 2299 virtual ~GetAllNodesRequestHelper(); 2300 2301 scoped_ptr<base::ListValue> result_accumulator_; 2302 2303 syncer::ModelTypeSet awaiting_types_; 2304 base::Callback<void(scoped_ptr<base::ListValue>)> callback_; 2305}; 2306 2307GetAllNodesRequestHelper::GetAllNodesRequestHelper( 2308 syncer::ModelTypeSet requested_types, 2309 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) 2310 : result_accumulator_(new base::ListValue()), 2311 awaiting_types_(requested_types), 2312 callback_(callback) {} 2313 2314GetAllNodesRequestHelper::~GetAllNodesRequestHelper() { 2315 if (!awaiting_types_.Empty()) { 2316 DLOG(WARNING) 2317 << "GetAllNodesRequest deleted before request was fulfilled. " 2318 << "Missing types are: " << ModelTypeSetToString(awaiting_types_); 2319 } 2320} 2321 2322// Called when the set of nodes for a type or set of types has been returned. 2323// 2324// The nodes for several types can be returned at the same time by specifying 2325// their types in the |types| array, and putting their results at the 2326// correspnding indices in the |scoped_node_lists|. 2327void GetAllNodesRequestHelper::OnReceivedNodesForTypes( 2328 const std::vector<syncer::ModelType>& types, 2329 ScopedVector<base::ListValue> scoped_node_lists) { 2330 DCHECK_EQ(types.size(), scoped_node_lists.size()); 2331 2332 // Take unsafe ownership of the node list. 2333 std::vector<base::ListValue*> node_lists; 2334 scoped_node_lists.release(&node_lists); 2335 2336 for (size_t i = 0; i < node_lists.size() && i < types.size(); ++i) { 2337 const ModelType type = types[i]; 2338 base::ListValue* node_list = node_lists[i]; 2339 2340 // Add these results to our list. 2341 scoped_ptr<base::DictionaryValue> type_dict(new base::DictionaryValue()); 2342 type_dict->SetString("type", ModelTypeToString(type)); 2343 type_dict->Set("nodes", node_list); 2344 result_accumulator_->Append(type_dict.release()); 2345 2346 // Remember that this part of the request is satisfied. 2347 awaiting_types_.Remove(type); 2348 } 2349 2350 if (awaiting_types_.Empty()) { 2351 callback_.Run(result_accumulator_.Pass()); 2352 callback_.Reset(); 2353 } 2354} 2355 2356} // namespace 2357 2358void ProfileSyncService::GetAllNodes( 2359 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback) { 2360 ModelTypeSet directory_types = GetRegisteredDirectoryDataTypes(); 2361 directory_types.PutAll(syncer::ControlTypes()); 2362 scoped_refptr<GetAllNodesRequestHelper> helper = 2363 new GetAllNodesRequestHelper(directory_types, callback); 2364 2365 if (!backend_initialized_) { 2366 // If there's no backend available to fulfill the request, handle it here. 2367 ScopedVector<base::ListValue> empty_results; 2368 std::vector<ModelType> type_vector; 2369 for (ModelTypeSet::Iterator it = directory_types.First(); 2370 it.Good(); it.Inc()) { 2371 type_vector.push_back(it.Get()); 2372 empty_results.push_back(new base::ListValue()); 2373 } 2374 helper->OnReceivedNodesForTypes(type_vector, empty_results.Pass()); 2375 } else { 2376 backend_->GetAllNodesForTypes( 2377 directory_types, 2378 base::Bind(&GetAllNodesRequestHelper::OnReceivedNodesForTypes, helper)); 2379 } 2380} 2381 2382bool ProfileSyncService::HasObserver( 2383 ProfileSyncServiceBase::Observer* observer) const { 2384 return observers_.HasObserver(observer); 2385} 2386 2387base::WeakPtr<syncer::JsController> ProfileSyncService::GetJsController() { 2388 return sync_js_controller_.AsWeakPtr(); 2389} 2390 2391void ProfileSyncService::SyncEvent(SyncEventCodes code) { 2392 UMA_HISTOGRAM_ENUMERATION("Sync.EventCodes", code, MAX_SYNC_EVENT_CODE); 2393} 2394 2395// static 2396bool ProfileSyncService::IsSyncEnabled() { 2397 // We have switches::kEnableSync just in case we need to change back to 2398 // sync-disabled-by-default on a platform. 2399 return !CommandLine::ForCurrentProcess()->HasSwitch(switches::kDisableSync); 2400} 2401 2402bool ProfileSyncService::IsManaged() const { 2403 return sync_prefs_.IsManaged() || sync_disabled_by_admin_; 2404} 2405 2406bool ProfileSyncService::ShouldPushChanges() { 2407 // True only after all bootstrapping has succeeded: the sync backend 2408 // is initialized, all enabled data types are consistent with one 2409 // another, and no unrecoverable error has transpired. 2410 if (HasUnrecoverableError()) 2411 return false; 2412 2413 if (!directory_data_type_manager_) 2414 return false; 2415 2416 return directory_data_type_manager_->state() == DataTypeManager::CONFIGURED; 2417} 2418 2419void ProfileSyncService::StopAndSuppress() { 2420 sync_prefs_.SetStartSuppressed(true); 2421 if (HasSyncingBackend()) { 2422 backend_->UnregisterInvalidationIds(); 2423 } 2424 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD); 2425} 2426 2427bool ProfileSyncService::IsStartSuppressed() const { 2428 return sync_prefs_.IsStartSuppressed(); 2429} 2430 2431SigninManagerBase* ProfileSyncService::signin() const { 2432 if (!signin_) 2433 return NULL; 2434 return signin_->GetOriginal(); 2435} 2436 2437void ProfileSyncService::UnsuppressAndStart() { 2438 DCHECK(profile_); 2439 sync_prefs_.SetStartSuppressed(false); 2440 // Set username in SigninManager, as SigninManager::OnGetUserInfoSuccess 2441 // is never called for some clients. 2442 if (signin_.get() && 2443 signin_->GetOriginal()->GetAuthenticatedUsername().empty()) { 2444 signin_->GetOriginal()->SetAuthenticatedUsername( 2445 profile_->GetPrefs()->GetString(prefs::kGoogleServicesUsername)); 2446 } 2447 startup_controller_.TryStart(); 2448} 2449 2450void ProfileSyncService::AcknowledgeSyncedTypes() { 2451 sync_prefs_.AcknowledgeSyncedTypes(GetRegisteredDataTypes()); 2452} 2453 2454void ProfileSyncService::ReconfigureDatatypeManager() { 2455 // If we haven't initialized yet, don't configure the DTM as it could cause 2456 // association to start before a Directory has even been created. 2457 if (backend_initialized_) { 2458 DCHECK(backend_.get()); 2459 ConfigureDataTypeManager(); 2460 } else if (HasUnrecoverableError()) { 2461 // There is nothing more to configure. So inform the listeners, 2462 NotifyObservers(); 2463 2464 DVLOG(1) << "ConfigureDataTypeManager not invoked because of an " 2465 << "Unrecoverable error."; 2466 } else { 2467 DVLOG(0) << "ConfigureDataTypeManager not invoked because backend is not " 2468 << "initialized"; 2469 } 2470} 2471 2472const FailedDataTypesHandler& ProfileSyncService::failed_data_types_handler() 2473 const { 2474 return failed_data_types_handler_; 2475} 2476 2477void ProfileSyncService::OnInternalUnrecoverableError( 2478 const tracked_objects::Location& from_here, 2479 const std::string& message, 2480 bool delete_sync_database, 2481 UnrecoverableErrorReason reason) { 2482 DCHECK(!HasUnrecoverableError()); 2483 unrecoverable_error_reason_ = reason; 2484 OnUnrecoverableErrorImpl(from_here, message, delete_sync_database); 2485} 2486 2487syncer::SyncManagerFactory::MANAGER_TYPE 2488ProfileSyncService::GetManagerType() const { 2489 switch (backend_mode_) { 2490 case SYNC: 2491 return syncer::SyncManagerFactory::NORMAL; 2492 case BACKUP: 2493 return syncer::SyncManagerFactory::BACKUP; 2494 case ROLLBACK: 2495 return syncer::SyncManagerFactory::ROLLBACK; 2496 case IDLE: 2497 NOTREACHED(); 2498 } 2499 return syncer::SyncManagerFactory::NORMAL; 2500} 2501 2502bool ProfileSyncService::IsRetryingAccessTokenFetchForTest() const { 2503 return request_access_token_retry_timer_.IsRunning(); 2504} 2505 2506std::string ProfileSyncService::GetAccessTokenForTest() const { 2507 return access_token_; 2508} 2509 2510WeakHandle<syncer::JsEventHandler> ProfileSyncService::GetJsEventHandler() { 2511 return MakeWeakHandle(sync_js_controller_.AsWeakPtr()); 2512} 2513 2514syncer::SyncableService* ProfileSyncService::GetSessionsSyncableService() { 2515 return sessions_sync_manager_.get(); 2516} 2517 2518ProfileSyncService::SyncTokenStatus::SyncTokenStatus() 2519 : connection_status(syncer::CONNECTION_NOT_ATTEMPTED), 2520 last_get_token_error(GoogleServiceAuthError::AuthErrorNone()) {} 2521ProfileSyncService::SyncTokenStatus::~SyncTokenStatus() {} 2522 2523ProfileSyncService::SyncTokenStatus 2524ProfileSyncService::GetSyncTokenStatus() const { 2525 SyncTokenStatus status; 2526 status.connection_status_update_time = connection_status_update_time_; 2527 status.connection_status = connection_status_; 2528 status.token_request_time = token_request_time_; 2529 status.token_receive_time = token_receive_time_; 2530 status.last_get_token_error = last_get_token_error_; 2531 if (request_access_token_retry_timer_.IsRunning()) 2532 status.next_token_request_time = next_token_request_time_; 2533 return status; 2534} 2535 2536void ProfileSyncService::OverrideNetworkResourcesForTest( 2537 scoped_ptr<syncer::NetworkResources> network_resources) { 2538 network_resources_ = network_resources.Pass(); 2539} 2540 2541bool ProfileSyncService::HasSyncingBackend() const { 2542 return backend_mode_ != SYNC ? false : backend_ != NULL; 2543} 2544 2545void ProfileSyncService::SetBackupStartDelayForTest(base::TimeDelta delay) { 2546 backup_start_delay_ = delay; 2547} 2548 2549void ProfileSyncService::UpdateFirstSyncTimePref() { 2550 if (signin_->GetEffectiveUsername().empty()) { 2551 // Clear if user's not signed in and rollback is done. 2552 if (backend_mode_ == BACKUP) 2553 sync_prefs_.ClearFirstSyncTime(); 2554 } else if (sync_prefs_.GetFirstSyncTime().is_null()) { 2555 // Set if user is signed in and time was not set before. 2556 sync_prefs_.SetFirstSyncTime(base::Time::Now()); 2557 } 2558} 2559 2560void ProfileSyncService::ClearBrowsingDataSinceFirstSync() { 2561 base::Time first_sync_time = sync_prefs_.GetFirstSyncTime(); 2562 if (first_sync_time.is_null()) 2563 return; 2564 2565 clear_browsing_data_.Run(profile_, first_sync_time, base::Time::Now()); 2566} 2567 2568void ProfileSyncService::SetClearingBrowseringDataForTesting( 2569 base::Callback<void(Profile*, base::Time, base::Time)> c) { 2570 clear_browsing_data_ = c; 2571} 2572 2573GURL ProfileSyncService::GetSyncServiceURL( 2574 const base::CommandLine& command_line) { 2575 // By default, dev, canary, and unbranded Chromium users will go to the 2576 // development servers. Development servers have more features than standard 2577 // sync servers. Users with officially-branded Chrome stable and beta builds 2578 // will go to the standard sync servers. 2579 GURL result(kDevServerUrl); 2580 2581 chrome::VersionInfo::Channel channel = chrome::VersionInfo::GetChannel(); 2582 if (channel == chrome::VersionInfo::CHANNEL_STABLE || 2583 channel == chrome::VersionInfo::CHANNEL_BETA) { 2584 result = GURL(kSyncServerUrl); 2585 } 2586 2587 // Override the sync server URL from the command-line, if sync server 2588 // command-line argument exists. 2589 if (command_line.HasSwitch(switches::kSyncServiceURL)) { 2590 std::string value(command_line.GetSwitchValueASCII( 2591 switches::kSyncServiceURL)); 2592 if (!value.empty()) { 2593 GURL custom_sync_url(value); 2594 if (custom_sync_url.is_valid()) { 2595 result = custom_sync_url; 2596 } else { 2597 LOG(WARNING) << "The following sync URL specified at the command-line " 2598 << "is invalid: " << value; 2599 } 2600 } 2601 } 2602 return result; 2603} 2604 2605void ProfileSyncService::StartStopBackupForTesting() { 2606 if (backend_mode_ == BACKUP) 2607 ShutdownImpl(browser_sync::SyncBackendHost::STOP_AND_CLAIM_THREAD); 2608 else 2609 backup_rollback_controller_.Start(base::TimeDelta()); 2610} 2611 2612void ProfileSyncService::CheckSyncBackupIfNeeded() { 2613 DCHECK_EQ(backend_mode_, SYNC); 2614 2615#if defined(ENABLE_PRE_SYNC_BACKUP) 2616 // Check backup once a day. 2617 if (!last_backup_time_ && 2618 (last_synced_time_.is_null() || 2619 base::Time::Now() - last_synced_time_ >= 2620 base::TimeDelta::FromDays(1))) { 2621 // If sync thread is set, need to serialize check on sync thread after 2622 // closing backup DB. 2623 if (sync_thread_) { 2624 sync_thread_->message_loop_proxy()->PostTask( 2625 FROM_HERE, 2626 base::Bind(syncer::CheckSyncDbLastModifiedTime, 2627 profile_->GetPath().Append(kSyncBackupDataFolderName), 2628 base::MessageLoopProxy::current(), 2629 base::Bind(&ProfileSyncService::CheckSyncBackupCallback, 2630 weak_factory_.GetWeakPtr()))); 2631 } else { 2632 content::BrowserThread::PostTask( 2633 content::BrowserThread::FILE, FROM_HERE, 2634 base::Bind(syncer::CheckSyncDbLastModifiedTime, 2635 profile_->GetPath().Append(kSyncBackupDataFolderName), 2636 base::MessageLoopProxy::current(), 2637 base::Bind(&ProfileSyncService::CheckSyncBackupCallback, 2638 weak_factory_.GetWeakPtr()))); 2639 } 2640 } 2641#endif 2642} 2643 2644void ProfileSyncService::CheckSyncBackupCallback(base::Time backup_time) { 2645 last_backup_time_.reset(new base::Time(backup_time)); 2646 2647 if (HasSyncingBackend() && backend_initialized_) { 2648 browser_sync::SyncedDeviceTracker* device_tracker = 2649 backend_->GetSyncedDeviceTracker(); 2650 if (device_tracker) 2651 device_tracker->UpdateLocalDeviceBackupTime(*last_backup_time_); 2652 } 2653} 2654 2655base::Time ProfileSyncService::GetDeviceBackupTimeForTesting() const { 2656 return backend_->GetSyncedDeviceTracker()->GetLocalDeviceBackupTime(); 2657} 2658