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