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