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