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