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