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