1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 6 #define CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 7 8 #include <string> 9 #include <utility> 10 #include <vector> 11 12 #include "base/basictypes.h" 13 #include "base/compiler_specific.h" 14 #include "base/gtest_prod_util.h" 15 #include "base/location.h" 16 #include "base/memory/scoped_ptr.h" 17 #include "base/memory/scoped_vector.h" 18 #include "base/memory/weak_ptr.h" 19 #include "base/observer_list.h" 20 #include "base/strings/string16.h" 21 #include "base/time/time.h" 22 #include "base/timer/timer.h" 23 #include "chrome/browser/sync/backend_unrecoverable_error_handler.h" 24 #include "chrome/browser/sync/backup_rollback_controller.h" 25 #include "chrome/browser/sync/glue/sync_backend_host.h" 26 #include "chrome/browser/sync/glue/synced_device_tracker.h" 27 #include "chrome/browser/sync/profile_sync_service_base.h" 28 #include "chrome/browser/sync/profile_sync_service_observer.h" 29 #include "chrome/browser/sync/protocol_event_observer.h" 30 #include "chrome/browser/sync/sessions/sessions_sync_manager.h" 31 #include "chrome/browser/sync/startup_controller.h" 32 #include "components/keyed_service/core/keyed_service.h" 33 #include "components/signin/core/browser/signin_manager_base.h" 34 #include "components/sync_driver/data_type_controller.h" 35 #include "components/sync_driver/data_type_encryption_handler.h" 36 #include "components/sync_driver/data_type_manager.h" 37 #include "components/sync_driver/data_type_manager_observer.h" 38 #include "components/sync_driver/failed_data_types_handler.h" 39 #include "components/sync_driver/non_blocking_data_type_manager.h" 40 #include "components/sync_driver/sync_frontend.h" 41 #include "components/sync_driver/sync_prefs.h" 42 #include "google_apis/gaia/google_service_auth_error.h" 43 #include "google_apis/gaia/oauth2_token_service.h" 44 #include "net/base/backoff_entry.h" 45 #include "sync/internal_api/public/base/model_type.h" 46 #include "sync/internal_api/public/engine/model_safe_worker.h" 47 #include "sync/internal_api/public/sync_manager_factory.h" 48 #include "sync/internal_api/public/util/experiments.h" 49 #include "sync/internal_api/public/util/unrecoverable_error_handler.h" 50 #include "sync/js/sync_js_controller.h" 51 #include "url/gurl.h" 52 53 class ManagedUserSigninManagerWrapper; 54 class Profile; 55 class ProfileOAuth2TokenService; 56 class ProfileSyncComponentsFactory; 57 class SyncErrorController; 58 59 namespace base { 60 class CommandLine; 61 }; 62 63 namespace browser_sync { 64 class BackendMigrator; 65 class ChangeProcessor; 66 class DataTypeManager; 67 class DeviceInfo; 68 class FaviconCache; 69 class JsController; 70 class OpenTabsUIDelegate; 71 72 namespace sessions { 73 class SyncSessionSnapshot; 74 } // namespace sessions 75 } // namespace browser_sync 76 77 namespace syncer { 78 class BaseTransaction; 79 class NetworkResources; 80 struct CommitCounters; 81 struct StatusCounters; 82 struct SyncCredentials; 83 struct UpdateCounters; 84 struct UserShare; 85 } // namespace syncer 86 87 namespace sync_pb { 88 class EncryptedData; 89 } // namespace sync_pb 90 91 using browser_sync::SessionsSyncManager; 92 93 // ProfileSyncService is the layer between browser subsystems like bookmarks, 94 // and the sync backend. Each subsystem is logically thought of as being 95 // a sync datatype. 96 // 97 // Individual datatypes can, at any point, be in a variety of stages of being 98 // "enabled". Here are some specific terms for concepts used in this class: 99 // 100 // 'Registered' (feature suppression for a datatype) 101 // 102 // When a datatype is registered, the user has the option of syncing it. 103 // The sync opt-in UI will show only registered types; a checkbox should 104 // never be shown for an unregistered type, and nor should it ever be 105 // synced. 106 // 107 // A datatype is considered registered once RegisterDataTypeController 108 // has been called with that datatype's DataTypeController. 109 // 110 // 'Preferred' (user preferences and opt-out for a datatype) 111 // 112 // This means the user's opt-in or opt-out preference on a per-datatype 113 // basis. The sync service will try to make active exactly these types. 114 // If a user has opted out of syncing a particular datatype, it will 115 // be registered, but not preferred. 116 // 117 // This state is controlled by the ConfigurePreferredDataTypes and 118 // GetPreferredDataTypes. They are stored in the preferences system, 119 // and persist; though if a datatype is not registered, it cannot 120 // be a preferred datatype. 121 // 122 // 'Active' (run-time initialization of sync system for a datatype) 123 // 124 // An active datatype is a preferred datatype that is actively being 125 // synchronized: the syncer has been instructed to querying the server 126 // for this datatype, first-time merges have finished, and there is an 127 // actively installed ChangeProcessor that listens for changes to this 128 // datatype, propagating such changes into and out of the sync backend 129 // as necessary. 130 // 131 // When a datatype is in the process of becoming active, it may be 132 // in some intermediate state. Those finer-grained intermediate states 133 // are differentiated by the DataTypeController state. 134 // 135 // Sync Configuration: 136 // 137 // Sync configuration is accomplished via the following APIs: 138 // * OnUserChoseDatatypes(): Set the data types the user wants to sync. 139 // * SetDecryptionPassphrase(): Attempt to decrypt the user's encrypted data 140 // using the passed passphrase. 141 // * SetEncryptionPassphrase(): Re-encrypt the user's data using the passed 142 // passphrase. 143 // 144 // Additionally, the current sync configuration can be fetched by calling 145 // * GetRegisteredDataTypes() 146 // * GetPreferredDataTypes() 147 // * GetActiveDataTypes() 148 // * IsUsingSecondaryPassphrase() 149 // * EncryptEverythingEnabled() 150 // * IsPassphraseRequired()/IsPassphraseRequiredForDecryption() 151 // 152 // The "sync everything" state cannot be read from ProfileSyncService, but 153 // is instead pulled from SyncPrefs.HasKeepEverythingSynced(). 154 // 155 // Initial sync setup: 156 // 157 // For privacy reasons, it is usually desirable to avoid syncing any data 158 // types until the user has finished setting up sync. There are two APIs 159 // that control the initial sync download: 160 // 161 // * SetSyncSetupCompleted() 162 // * SetSetupInProgress() 163 // 164 // SetSyncSetupCompleted() should be called once the user has finished setting 165 // up sync at least once on their account. SetSetupInProgress(true) should be 166 // called while the user is actively configuring their account, and then 167 // SetSetupInProgress(false) should be called when configuration is complete. 168 // When SetSyncSetupCompleted() == false, but SetSetupInProgress(true) has 169 // been called, then the sync engine knows not to download any user data. 170 // 171 // When initial sync is complete, the UI code should call 172 // SetSyncSetupCompleted() followed by SetSetupInProgress(false) - this will 173 // tell the sync engine that setup is completed and it can begin downloading 174 // data from the sync server. 175 // 176 class ProfileSyncService : public ProfileSyncServiceBase, 177 public browser_sync::SyncFrontend, 178 public sync_driver::SyncPrefObserver, 179 public browser_sync::DataTypeManagerObserver, 180 public syncer::UnrecoverableErrorHandler, 181 public KeyedService, 182 public browser_sync::DataTypeEncryptionHandler, 183 public OAuth2TokenService::Consumer, 184 public OAuth2TokenService::Observer, 185 public SessionsSyncManager::SyncInternalApiDelegate, 186 public SigninManagerBase::Observer { 187 public: 188 typedef browser_sync::SyncBackendHost::Status Status; 189 190 // Status of sync server connection, sync token and token request. 191 struct SyncTokenStatus { 192 SyncTokenStatus(); 193 ~SyncTokenStatus(); 194 195 // Sync server connection status reported by sync backend. 196 base::Time connection_status_update_time; 197 syncer::ConnectionStatus connection_status; 198 199 // Times when OAuth2 access token is requested and received. 200 base::Time token_request_time; 201 base::Time token_receive_time; 202 203 // Error returned by OAuth2TokenService for token request and time when 204 // next request is scheduled. 205 GoogleServiceAuthError last_get_token_error; 206 base::Time next_token_request_time; 207 }; 208 209 enum SyncEventCodes { 210 MIN_SYNC_EVENT_CODE = 0, 211 212 // Events starting the sync service. 213 START_FROM_NTP = 1, // Sync was started from the ad in NTP 214 START_FROM_WRENCH = 2, // Sync was started from the Wrench menu. 215 START_FROM_OPTIONS = 3, // Sync was started from Wrench->Options. 216 START_FROM_BOOKMARK_MANAGER = 4, // Sync was started from Bookmark manager. 217 START_FROM_PROFILE_MENU = 5, // Sync was started from multiprofile menu. 218 START_FROM_URL = 6, // Sync was started from a typed URL. 219 220 // Events regarding cancellation of the signon process of sync. 221 CANCEL_FROM_SIGNON_WITHOUT_AUTH = 10, // Cancelled before submitting 222 // username and password. 223 CANCEL_DURING_SIGNON = 11, // Cancelled after auth. 224 CANCEL_DURING_CONFIGURE = 12, // Cancelled before choosing data 225 // types and clicking OK. 226 // Events resulting in the stoppage of sync service. 227 STOP_FROM_OPTIONS = 20, // Sync was stopped from Wrench->Options. 228 STOP_FROM_ADVANCED_DIALOG = 21, // Sync was stopped via advanced settings. 229 230 // Miscellaneous events caused by sync service. 231 232 MAX_SYNC_EVENT_CODE 233 }; 234 235 // Used to specify the kind of passphrase with which sync data is encrypted. 236 enum PassphraseType { 237 IMPLICIT, // The user did not provide a custom passphrase for encryption. 238 // We implicitly use the GAIA password in such cases. 239 EXPLICIT, // The user selected the "use custom passphrase" radio button 240 // during sync setup and provided a passphrase. 241 }; 242 243 enum SyncStatusSummary { 244 UNRECOVERABLE_ERROR, 245 NOT_ENABLED, 246 SETUP_INCOMPLETE, 247 DATATYPES_NOT_INITIALIZED, 248 INITIALIZED, 249 BACKUP_USER_DATA, 250 ROLLBACK_USER_DATA, 251 UNKNOWN_ERROR, 252 }; 253 254 enum BackendMode { 255 IDLE, // No backend. 256 SYNC, // Backend for syncing. 257 BACKUP, // Backend for backup. 258 ROLLBACK // Backend for rollback. 259 }; 260 261 // Default sync server URL. 262 static const char* kSyncServerUrl; 263 // Sync server URL for dev channel users 264 static const char* kDevServerUrl; 265 266 // Takes ownership of |factory| and |signin_wrapper|. 267 ProfileSyncService( 268 ProfileSyncComponentsFactory* factory, 269 Profile* profile, 270 scoped_ptr<ManagedUserSigninManagerWrapper> signin_wrapper, 271 ProfileOAuth2TokenService* oauth2_token_service, 272 browser_sync::ProfileSyncServiceStartBehavior start_behavior); 273 virtual ~ProfileSyncService(); 274 275 // Initializes the object. This must be called at most once, and 276 // immediately after an object of this class is constructed. 277 void Initialize(); 278 279 virtual void SetSyncSetupCompleted(); 280 281 // ProfileSyncServiceBase implementation. 282 virtual bool HasSyncSetupCompleted() const OVERRIDE; 283 virtual bool ShouldPushChanges() OVERRIDE; 284 virtual syncer::ModelTypeSet GetActiveDataTypes() const OVERRIDE; 285 virtual void AddObserver(ProfileSyncServiceBase::Observer* observer) OVERRIDE; 286 virtual void RemoveObserver( 287 ProfileSyncServiceBase::Observer* observer) OVERRIDE; 288 virtual bool HasObserver( 289 ProfileSyncServiceBase::Observer* observer) const OVERRIDE; 290 291 292 void AddProtocolEventObserver(browser_sync::ProtocolEventObserver* observer); 293 void RemoveProtocolEventObserver( 294 browser_sync::ProtocolEventObserver* observer); 295 296 void AddTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer); 297 void RemoveTypeDebugInfoObserver(syncer::TypeDebugInfoObserver* observer); 298 299 // Asynchronously fetches base::Value representations of all sync nodes and 300 // returns them to the specified callback on this thread. 301 // 302 // These requests can live a long time and return when you least expect it. 303 // For safety, the callback should be bound to some sort of WeakPtr<> or 304 // scoped_refptr<>. 305 void GetAllNodes( 306 const base::Callback<void(scoped_ptr<base::ListValue>)>& callback); 307 308 void RegisterAuthNotifications(); 309 void UnregisterAuthNotifications(); 310 311 // Returns true if sync is enabled/not suppressed and the user is logged in. 312 // (being logged in does not mean that tokens are available - tokens may 313 // be missing because they have not loaded yet, or because they were deleted 314 // due to http://crbug.com/121755). 315 // Virtual to enable mocking in tests. 316 // TODO(tim): Remove this? Nothing in ProfileSyncService uses it, and outside 317 // callers use a seemingly arbitrary / redundant / bug prone combination of 318 // this method, IsSyncAccessible, and others. 319 virtual bool IsSyncEnabledAndLoggedIn(); 320 321 // Return whether OAuth2 refresh token is loaded and available for the backend 322 // to start up. Virtual to enable mocking in tests. 323 virtual bool IsOAuthRefreshTokenAvailable(); 324 325 // Registers a data type controller with the sync service. This 326 // makes the data type controller available for use, it does not 327 // enable or activate the synchronization of the data type (see 328 // ActivateDataType). Takes ownership of the pointer. 329 void RegisterDataTypeController( 330 browser_sync::DataTypeController* data_type_controller); 331 332 // Registers a type whose sync storage will not be managed by the 333 // ProfileSyncService. It declares that this sync type may be activated at 334 // some point in the future. This function call does not enable or activate 335 // the syncing of this type 336 void RegisterNonBlockingType(syncer::ModelType type); 337 338 // Called by a component that supports non-blocking sync when it is ready to 339 // initialize its connection to the sync backend. 340 // 341 // If policy allows for syncing this type (ie. it is "preferred"), then this 342 // should result in a message to enable syncing for this type when the sync 343 // backend is available. If the type is not to be synced, this should result 344 // in a message that allows the component to delete its local sync state. 345 void InitializeNonBlockingType( 346 syncer::ModelType type, 347 scoped_refptr<base::SequencedTaskRunner> task_runner, 348 base::WeakPtr<syncer::NonBlockingTypeProcessor> processor); 349 350 // Return the active OpenTabsUIDelegate. If sessions is not enabled or not 351 // currently syncing, returns NULL. 352 virtual browser_sync::OpenTabsUIDelegate* GetOpenTabsUIDelegate(); 353 354 // Returns the SyncableService for syncer::SESSIONS. 355 virtual syncer::SyncableService* GetSessionsSyncableService(); 356 357 // SyncInternalApiDelegate implementation. 358 // 359 // Returns sync's representation of the local device info. 360 // Return value is an empty scoped_ptr if the device info is unavailable. 361 virtual scoped_ptr<browser_sync::DeviceInfo> GetLocalDeviceInfo() 362 const OVERRIDE; 363 364 // Gets the guid for the local device. Can be used by other layers to 365 // to distinguish sync data that belongs to the local device vs data 366 // that belongs to remote devices. Returns empty string if sync is not 367 // initialized. The GUID is not persistent across Chrome signout/signin. 368 // If you sign out of Chrome and sign in, a new GUID is generated. 369 virtual std::string GetLocalSyncCacheGUID() const OVERRIDE; 370 371 // Returns sync's representation of the device info for a client identified 372 // by |client_id|. Return value is an empty scoped ptr if the device info 373 // is unavailable. 374 virtual scoped_ptr<browser_sync::DeviceInfo> GetDeviceInfo( 375 const std::string& client_id) const; 376 377 // Gets the device info for all devices signed into the account associated 378 // with this profile. 379 virtual ScopedVector<browser_sync::DeviceInfo> GetAllSignedInDevices() const; 380 381 // Notifies the observer of any device info changes. 382 virtual void AddObserverForDeviceInfoChange( 383 browser_sync::SyncedDeviceTracker::Observer* observer); 384 385 // Removes the observer from device info notification. 386 virtual void RemoveObserverForDeviceInfoChange( 387 browser_sync::SyncedDeviceTracker::Observer* observer); 388 389 // Fills state_map with a map of current data types that are possible to 390 // sync, as well as their states. 391 void GetDataTypeControllerStates( 392 browser_sync::DataTypeController::StateMap* state_map) const; 393 394 // Disables sync for user. Use ShowLoginDialog to enable. 395 virtual void DisableForUser(); 396 397 // Disables sync for the user and prevents it from starting on next restart. 398 virtual void StopSyncingPermanently(); 399 400 // SyncFrontend implementation. 401 virtual void OnBackendInitialized( 402 const syncer::WeakHandle<syncer::JsBackend>& js_backend, 403 const syncer::WeakHandle<syncer::DataTypeDebugInfoListener>& 404 debug_info_listener, 405 bool success) OVERRIDE; 406 virtual void OnSyncCycleCompleted() OVERRIDE; 407 virtual void OnProtocolEvent(const syncer::ProtocolEvent& event) OVERRIDE; 408 virtual void OnDirectoryTypeCommitCounterUpdated( 409 syncer::ModelType type, 410 const syncer::CommitCounters& counters) OVERRIDE; 411 virtual void OnDirectoryTypeUpdateCounterUpdated( 412 syncer::ModelType type, 413 const syncer::UpdateCounters& counters) OVERRIDE; 414 virtual void OnDirectoryTypeStatusCounterUpdated( 415 syncer::ModelType type, 416 const syncer::StatusCounters& counters) OVERRIDE; 417 virtual void OnSyncConfigureRetry() OVERRIDE; 418 virtual void OnConnectionStatusChange( 419 syncer::ConnectionStatus status) OVERRIDE; 420 virtual void OnPassphraseRequired( 421 syncer::PassphraseRequiredReason reason, 422 const sync_pb::EncryptedData& pending_keys) OVERRIDE; 423 virtual void OnPassphraseAccepted() OVERRIDE; 424 virtual void OnEncryptedTypesChanged( 425 syncer::ModelTypeSet encrypted_types, 426 bool encrypt_everything) OVERRIDE; 427 virtual void OnEncryptionComplete() OVERRIDE; 428 virtual void OnMigrationNeededForTypes( 429 syncer::ModelTypeSet types) OVERRIDE; 430 virtual void OnExperimentsChanged( 431 const syncer::Experiments& experiments) OVERRIDE; 432 virtual void OnActionableError( 433 const syncer::SyncProtocolError& error) OVERRIDE; 434 435 // DataTypeManagerObserver implementation. 436 virtual void OnConfigureDone( 437 const browser_sync::DataTypeManager::ConfigureResult& result) OVERRIDE; 438 virtual void OnConfigureRetry() OVERRIDE; 439 virtual void OnConfigureStart() OVERRIDE; 440 441 // DataTypeEncryptionHandler implementation. 442 virtual bool IsPassphraseRequired() const OVERRIDE; 443 virtual syncer::ModelTypeSet GetEncryptedDataTypes() const OVERRIDE; 444 445 // SigninManagerBase::Observer implementation. 446 virtual void GoogleSigninSucceeded(const std::string& username, 447 const std::string& password) OVERRIDE; 448 virtual void GoogleSignedOut(const std::string& username) OVERRIDE; 449 450 // Called when a user chooses which data types to sync as part of the sync 451 // setup wizard. |sync_everything| represents whether they chose the 452 // "keep everything synced" option; if true, |chosen_types| will be ignored 453 // and all data types will be synced. |sync_everything| means "sync all 454 // current and future data types." 455 virtual void OnUserChoseDatatypes(bool sync_everything, 456 syncer::ModelTypeSet chosen_types); 457 458 // Get the sync status code. 459 SyncStatusSummary QuerySyncStatusSummary(); 460 461 // Get a description of the sync status for displaying in the user interface. 462 std::string QuerySyncStatusSummaryString(); 463 464 // Initializes a struct of status indicators with data from the backend. 465 // Returns false if the backend was not available for querying; in that case 466 // the struct will be filled with default data. 467 virtual bool QueryDetailedSyncStatus( 468 browser_sync::SyncBackendHost::Status* result); 469 470 virtual const GoogleServiceAuthError& GetAuthError() const; 471 472 // Returns true if initial sync setup is in progress (does not return true 473 // if the user is customizing sync after already completing setup once). 474 // ProfileSyncService uses this to determine if it's OK to start syncing, or 475 // if the user is still setting up the initial sync configuration. 476 virtual bool FirstSetupInProgress() const; 477 478 // Called by the UI to notify the ProfileSyncService that UI is visible so it 479 // will not start syncing. This tells sync whether it's safe to start 480 // downloading data types yet (we don't start syncing until after sync setup 481 // is complete). The UI calls this as soon as any part of the signin wizard is 482 // displayed (even just the login UI). 483 // If |setup_in_progress| is false, this also kicks the sync engine to ensure 484 // that data download starts. 485 virtual void SetSetupInProgress(bool setup_in_progress); 486 487 // Returns true if the SyncBackendHost has told us it's ready to accept 488 // changes. 489 // [REMARK] - it is safe to call this function only from the ui thread. 490 // because the variable is not thread safe and should only be accessed from 491 // single thread. If we want multiple threads to access this(and there is 492 // currently no need to do so) we need to protect this with a lock. 493 // TODO(timsteele): What happens if the bookmark model is loaded, a change 494 // takes place, and the backend isn't initialized yet? 495 virtual bool sync_initialized() const; 496 497 virtual bool HasUnrecoverableError() const; unrecoverable_error_message()498 const std::string& unrecoverable_error_message() { 499 return unrecoverable_error_message_; 500 } unrecoverable_error_location()501 tracked_objects::Location unrecoverable_error_location() { 502 return unrecoverable_error_location_; 503 } 504 505 // Returns true if OnPassphraseRequired has been called for decryption and 506 // we have an encrypted data type enabled. 507 virtual bool IsPassphraseRequiredForDecryption() const; 508 passphrase_required_reason()509 syncer::PassphraseRequiredReason passphrase_required_reason() const { 510 return passphrase_required_reason_; 511 } 512 513 // Returns a user-friendly string form of last synced time (in minutes). 514 virtual base::string16 GetLastSyncedTimeString() const; 515 516 // Returns a human readable string describing backend initialization state. 517 std::string GetBackendInitializationStateString() const; 518 519 // Returns true if startup is suppressed (i.e. user has stopped syncing via 520 // the google dashboard). 521 virtual bool IsStartSuppressed() const; 522 factory()523 ProfileSyncComponentsFactory* factory() { return factory_.get(); } 524 525 // The profile we are syncing for. profile()526 Profile* profile() const { return profile_; } 527 528 // Returns a weak pointer to the service's JsController. 529 // Overrideable for testing purposes. 530 virtual base::WeakPtr<syncer::JsController> GetJsController(); 531 532 // Record stats on various events. 533 static void SyncEvent(SyncEventCodes code); 534 535 // Returns whether sync is enabled. Sync can be enabled/disabled both 536 // at compile time (e.g., on a per-OS basis) or at run time (e.g., 537 // command-line switches). 538 // Profile::IsSyncAccessible() is probably a better signal than this function. 539 // This function can be called from any thread, and the implementation doesn't 540 // assume it's running on the UI thread. 541 static bool IsSyncEnabled(); 542 543 // Returns whether sync is managed, i.e. controlled by configuration 544 // management. If so, the user is not allowed to configure sync. 545 virtual bool IsManaged() const; 546 547 // syncer::UnrecoverableErrorHandler implementation. 548 virtual void OnUnrecoverableError( 549 const tracked_objects::Location& from_here, 550 const std::string& message) OVERRIDE; 551 552 // Called when a datatype wishes to disable itself. Note, this does not change 553 // preferred state of a datatype and is not persisted across restarts. 554 virtual void DisableDatatype(syncer::ModelType type, 555 const tracked_objects::Location& from_here, 556 std::string message); 557 558 // Called to re-enable a type disabled by DisableDatatype(..). Note, this does 559 // not change the preferred state of a datatype, and is not persisted across 560 // restarts. 561 void ReenableDatatype(syncer::ModelType type); 562 563 // The functions below (until ActivateDataType()) should only be 564 // called if sync_initialized() is true. 565 566 // TODO(akalin): This is called mostly by ModelAssociators and 567 // tests. Figure out how to pass the handle to the ModelAssociators 568 // directly, figure out how to expose this to tests, and remove this 569 // function. 570 virtual syncer::UserShare* GetUserShare() const; 571 572 // TODO(akalin): These two functions are used only by 573 // ProfileSyncServiceHarness. Figure out a different way to expose 574 // this info to that class, and remove these functions. 575 576 virtual syncer::sessions::SyncSessionSnapshot 577 GetLastSessionSnapshot() const; 578 579 // Returns whether or not the underlying sync engine has made any 580 // local changes to items that have not yet been synced with the 581 // server. 582 bool HasUnsyncedItems() const; 583 584 // Used by ProfileSyncServiceHarness. May return NULL. 585 browser_sync::BackendMigrator* GetBackendMigratorForTest(); 586 587 // Used by tests to inspect interaction with OAuth2TokenService. 588 bool IsRetryingAccessTokenFetchForTest() const; 589 590 // Used by tests to inspect the OAuth2 access tokens used by PSS. 591 std::string GetAccessTokenForTest() const; 592 593 // TODO(sync): This is only used in tests. Can we remove it? 594 void GetModelSafeRoutingInfo(syncer::ModelSafeRoutingInfo* out) const; 595 596 // Returns a ListValue indicating the status of all registered types. 597 // 598 // The format is: 599 // [ {"name": <name>, "value": <value>, "status": <status> }, ... ] 600 // where <name> is a type's name, <value> is a string providing details for 601 // the type's status, and <status> is one of "error", "warning" or "ok" 602 // depending on the type's current status. 603 // 604 // This function is used by about_sync_util.cc to help populate the about:sync 605 // page. It returns a ListValue rather than a DictionaryValue in part to make 606 // it easier to iterate over its elements when constructing that page. 607 base::Value* GetTypeStatusMap() const; 608 609 // Overridden by tests. 610 // TODO(zea): Remove these and have the dtc's call directly into the SBH. 611 virtual void DeactivateDataType(syncer::ModelType type); 612 613 // SyncPrefObserver implementation. 614 virtual void OnSyncManagedPrefChange(bool is_sync_managed) OVERRIDE; 615 616 // Changes which data types we're going to be syncing to |preferred_types|. 617 // If it is running, the DataTypeManager will be instructed to reconfigure 618 // the sync backend so that exactly these datatypes are actively synced. See 619 // class comment for more on what it means for a datatype to be Preferred. 620 virtual void ChangePreferredDataTypes( 621 syncer::ModelTypeSet preferred_types); 622 623 // Returns the set of types which are preferred for enabling. This is a 624 // superset of the active types (see GetActiveDataTypes()). 625 virtual syncer::ModelTypeSet GetPreferredDataTypes() const; 626 627 // Returns the set of directory types which are preferred for enabling. 628 virtual syncer::ModelTypeSet GetPreferredDirectoryDataTypes() const; 629 630 // Returns the set of off-thread types which are preferred for enabling. 631 virtual syncer::ModelTypeSet GetPreferredNonBlockingDataTypes() const; 632 633 // Gets the set of all data types that could be allowed (the set that 634 // should be advertised to the user). These will typically only change 635 // via a command-line option. See class comment for more on what it means 636 // for a datatype to be Registered. 637 virtual syncer::ModelTypeSet GetRegisteredDataTypes() const; 638 639 // Gets the set of directory types which could be allowed. 640 virtual syncer::ModelTypeSet GetRegisteredDirectoryDataTypes() const; 641 642 // Gets the set of off-thread types which could be allowed. 643 virtual syncer::ModelTypeSet GetRegisteredNonBlockingDataTypes() const; 644 645 // Checks whether the Cryptographer is ready to encrypt and decrypt updates 646 // for sensitive data types. Caller must be holding a 647 // syncapi::BaseTransaction to ensure thread safety. 648 virtual bool IsCryptographerReady( 649 const syncer::BaseTransaction* trans) const; 650 651 // Returns true if a secondary (explicit) passphrase is being used. It is not 652 // legal to call this method before the backend is initialized. 653 virtual bool IsUsingSecondaryPassphrase() const; 654 655 // Returns the actual passphrase type being used for encryption. 656 virtual syncer::PassphraseType GetPassphraseType() const; 657 658 // Returns the time the current explicit passphrase (if any), was set. 659 // If no secondary passphrase is in use, or no time is available, returns an 660 // unset base::Time. 661 virtual base::Time GetExplicitPassphraseTime() const; 662 663 // Note about setting passphrases: There are different scenarios under which 664 // we might want to apply a passphrase. It could be for first-time encryption, 665 // re-encryption, or for decryption by clients that sign in at a later time. 666 // In addition, encryption can either be done using a custom passphrase, or by 667 // reusing the GAIA password. Depending on what is happening in the system, 668 // callers should determine which of the two methods below must be used. 669 670 // Asynchronously sets the passphrase to |passphrase| for encryption. |type| 671 // specifies whether the passphrase is a custom passphrase or the GAIA 672 // password being reused as a passphrase. 673 // TODO(atwilson): Change this so external callers can only set an EXPLICIT 674 // passphrase with this API. 675 virtual void SetEncryptionPassphrase(const std::string& passphrase, 676 PassphraseType type); 677 678 // Asynchronously decrypts pending keys using |passphrase|. Returns false 679 // immediately if the passphrase could not be used to decrypt a locally cached 680 // copy of encrypted keys; returns true otherwise. 681 virtual bool SetDecryptionPassphrase(const std::string& passphrase) 682 WARN_UNUSED_RESULT; 683 684 // Turns on encryption for all data. Callers must call OnUserChoseDatatypes() 685 // after calling this to force the encryption to occur. 686 virtual void EnableEncryptEverything(); 687 688 // Returns true if we are currently set to encrypt all the sync data. Note: 689 // this is based on the cryptographer's settings, so if the user has recently 690 // requested encryption to be turned on, this may not be true yet. For that, 691 // encryption_pending() must be checked. 692 virtual bool EncryptEverythingEnabled() const; 693 694 // Returns true if the syncer is waiting for new datatypes to be encrypted. 695 virtual bool encryption_pending() const; 696 sync_service_url()697 const GURL& sync_service_url() const { return sync_service_url_; } 698 SigninManagerBase* signin() const; 699 700 // Used by tests. 701 bool auto_start_enabled() const; 702 bool setup_in_progress() const; 703 704 // Stops the sync backend and sets the flag for suppressing sync startup. 705 void StopAndSuppress(); 706 707 // Resets the flag for suppressing sync startup and starts the sync backend. 708 virtual void UnsuppressAndStart(); 709 710 // Marks all currently registered types as "acknowledged" so we won't prompt 711 // the user about them any more. 712 void AcknowledgeSyncedTypes(); 713 sync_error_controller()714 SyncErrorController* sync_error_controller() { 715 return sync_error_controller_.get(); 716 } 717 718 // TODO(sync): This is only used in tests. Can we remove it? 719 const browser_sync::FailedDataTypesHandler& failed_data_types_handler() const; 720 configure_status()721 browser_sync::DataTypeManager::ConfigureStatus configure_status() { 722 return configure_status_; 723 } 724 725 // If true, the ProfileSyncService has detected that a new GAIA signin has 726 // succeeded, and is waiting for initialization to complete. This is used by 727 // the UI to differentiate between a new auth error (encountered as part of 728 // the initialization process) and a pre-existing auth error that just hasn't 729 // been cleared yet. Virtual for testing purposes. 730 virtual bool waiting_for_auth() const; 731 732 // The set of currently enabled sync experiments. 733 const syncer::Experiments& current_experiments() const; 734 735 // OAuth2TokenService::Consumer implementation. 736 virtual void OnGetTokenSuccess( 737 const OAuth2TokenService::Request* request, 738 const std::string& access_token, 739 const base::Time& expiration_time) OVERRIDE; 740 virtual void OnGetTokenFailure( 741 const OAuth2TokenService::Request* request, 742 const GoogleServiceAuthError& error) OVERRIDE; 743 744 // OAuth2TokenService::Observer implementation. 745 virtual void OnRefreshTokenAvailable(const std::string& account_id) OVERRIDE; 746 virtual void OnRefreshTokenRevoked(const std::string& account_id) OVERRIDE; 747 virtual void OnRefreshTokensLoaded() OVERRIDE; 748 749 // KeyedService implementation. This must be called exactly 750 // once (before this object is destroyed). 751 virtual void Shutdown() OVERRIDE; 752 753 // Called when a datatype (SyncableService) has a need for sync to start 754 // ASAP, presumably because a local change event has occurred but we're 755 // still in deferred start mode, meaning the SyncableService hasn't been 756 // told to MergeDataAndStartSyncing yet. 757 void OnDataTypeRequestsSyncStartup(syncer::ModelType type); 758 759 // Return sync token status. 760 SyncTokenStatus GetSyncTokenStatus() const; 761 762 browser_sync::FaviconCache* GetFaviconCache(); 763 764 // Overrides the NetworkResources used for Sync connections. 765 // This function takes ownership of |network_resources|. 766 void OverrideNetworkResourcesForTest( 767 scoped_ptr<syncer::NetworkResources> network_resources); 768 769 virtual bool IsSessionsDataTypeControllerRunning() const; 770 771 void SetBackupStartDelayForTest(base::TimeDelta delay); 772 backend_mode()773 BackendMode backend_mode() const { 774 return backend_mode_; 775 } 776 777 void SetClearingBrowseringDataForTesting( 778 base::Callback<void(Profile*, base::Time, base::Time)> c); 779 780 // Return the base URL of the Sync Server. 781 static GURL GetSyncServiceURL(const base::CommandLine& command_line); 782 783 void StartStopBackupForTesting(); 784 785 protected: 786 // Helper to configure the priority data types. 787 void ConfigurePriorityDataTypes(); 788 789 // Helper to install and configure a data type manager. 790 void ConfigureDataTypeManager(); 791 792 // Shuts down the backend sync components. 793 // |option| indicates if syncing is being disabled or not, and whether 794 // to claim ownership of sync thread from backend. 795 void ShutdownImpl(browser_sync::SyncBackendHost::ShutdownOption option); 796 797 // Return SyncCredentials from the OAuth2TokenService. 798 syncer::SyncCredentials GetCredentials(); 799 800 virtual syncer::WeakHandle<syncer::JsEventHandler> GetJsEventHandler(); 801 802 const browser_sync::DataTypeController::TypeMap& directory_data_type_controllers()803 directory_data_type_controllers() { 804 return directory_data_type_controllers_; 805 } 806 807 // Helper method for managing encryption UI. 808 bool IsEncryptedDatatypeEnabled() const; 809 810 // Helper for OnUnrecoverableError. 811 // TODO(tim): Use an enum for |delete_sync_database| here, in ShutdownImpl, 812 // and in SyncBackendHost::Shutdown. 813 void OnUnrecoverableErrorImpl( 814 const tracked_objects::Location& from_here, 815 const std::string& message, 816 bool delete_sync_database); 817 818 // This is a cache of the last authentication response we received from the 819 // sync server. The UI queries this to display appropriate messaging to the 820 // user. 821 GoogleServiceAuthError last_auth_error_; 822 823 // Our asynchronous backend to communicate with sync components living on 824 // other threads. 825 scoped_ptr<browser_sync::SyncBackendHost> backend_; 826 827 // Was the last SYNC_PASSPHRASE_REQUIRED notification sent because it 828 // was required for encryption, decryption with a cached passphrase, or 829 // because a new passphrase is required? 830 syncer::PassphraseRequiredReason passphrase_required_reason_; 831 832 private: 833 enum UnrecoverableErrorReason { 834 ERROR_REASON_UNSET, 835 ERROR_REASON_SYNCER, 836 ERROR_REASON_BACKEND_INIT_FAILURE, 837 ERROR_REASON_CONFIGURATION_RETRY, 838 ERROR_REASON_CONFIGURATION_FAILURE, 839 ERROR_REASON_ACTIONABLE_ERROR, 840 ERROR_REASON_LIMIT 841 }; 842 843 enum AuthErrorMetric { 844 AUTH_ERROR_ENCOUNTERED, 845 AUTH_ERROR_FIXED, 846 AUTH_ERROR_LIMIT 847 }; 848 849 friend class ProfileSyncServicePasswordTest; 850 friend class SyncTest; 851 friend class TestProfileSyncService; 852 FRIEND_TEST_ALL_PREFIXES(ProfileSyncServiceTest, InitialState); 853 854 // Update the last auth error and notify observers of error state. 855 void UpdateAuthErrorState(const GoogleServiceAuthError& error); 856 857 // Detects and attempts to recover from a previous improper datatype 858 // configuration where Keep Everything Synced and the preferred types were 859 // not correctly set. 860 void TrySyncDatatypePrefRecovery(); 861 862 // Puts the backend's sync scheduler into NORMAL mode. 863 // Called when configuration is complete. 864 void StartSyncingWithServer(); 865 866 // Called when we've determined that we don't need a passphrase (either 867 // because OnPassphraseAccepted() was called, or because we've gotten a 868 // OnPassphraseRequired() but no data types are enabled). 869 void ResolvePassphraseRequired(); 870 871 // During initial signin, ProfileSyncService caches the user's signin 872 // passphrase so it can be used to encrypt/decrypt data after sync starts up. 873 // This routine is invoked once the backend has started up to use the 874 // cached passphrase and clear it out when it is done. 875 void ConsumeCachedPassphraseIfPossible(); 876 877 // RequestAccessToken initiates RPC to request downscoped access token from 878 // refresh token. This happens when a new OAuth2 login token is loaded and 879 // when sync server returns AUTH_ERROR which indicates it is time to refresh 880 // token. 881 virtual void RequestAccessToken(); 882 883 // Return true if backend should start from a fresh sync DB. 884 bool ShouldDeleteSyncFolder(); 885 886 // If |delete_sync_data_folder| is true, then this method will delete all 887 // previous "Sync Data" folders. (useful if the folder is partial/corrupt). 888 void InitializeBackend(bool delete_sync_data_folder); 889 890 // Initializes the various settings from the command line. 891 void InitSettings(); 892 893 // Sets the last synced time to the current time. 894 void UpdateLastSyncedTime(); 895 896 void NotifyObservers(); 897 void NotifySyncCycleCompleted(); 898 899 void ClearStaleErrors(); 900 901 void ClearUnrecoverableError(); 902 903 // Starts up the backend sync components. |mode| specifies the kind of 904 // backend to start, one of SYNC, BACKUP or ROLLBACK. 905 virtual void StartUpSlowBackendComponents(BackendMode mode); 906 907 // About-flags experiment names for datatypes that aren't enabled by default 908 // yet. 909 static std::string GetExperimentNameForDataType( 910 syncer::ModelType data_type); 911 912 // Create and register a new datatype controller. 913 void RegisterNewDataType(syncer::ModelType data_type); 914 915 // Reconfigures the data type manager with the latest enabled types. 916 // Note: Does not initialize the backend if it is not already initialized. 917 // This function needs to be called only after sync has been initialized 918 // (i.e.,only for reconfigurations). The reason we don't initialize the 919 // backend is because if we had encountered an unrecoverable error we don't 920 // want to startup once more. 921 virtual void ReconfigureDatatypeManager(); 922 923 // Called when the user changes the sync configuration, to update the UMA 924 // stats. 925 void UpdateSelectedTypesHistogram( 926 bool sync_everything, 927 const syncer::ModelTypeSet chosen_types) const; 928 929 #if defined(OS_CHROMEOS) 930 // Refresh spare sync bootstrap token for re-enabling the sync service. 931 // Called on successful sign-in notifications. 932 void RefreshSpareBootstrapToken(const std::string& passphrase); 933 #endif 934 935 // Internal unrecoverable error handler. Used to track error reason via 936 // Sync.UnrecoverableErrors histogram. 937 void OnInternalUnrecoverableError(const tracked_objects::Location& from_here, 938 const std::string& message, 939 bool delete_sync_database, 940 UnrecoverableErrorReason reason); 941 942 // Returns the type of manager to use according to |backend_mode_|. 943 syncer::SyncManagerFactory::MANAGER_TYPE GetManagerType() const; 944 945 // Update UMA for syncing backend. 946 void UpdateBackendInitUMA(bool success); 947 948 // Various setup following backend initialization, mostly for syncing backend. 949 void PostBackendInitialization(); 950 951 // True if a syncing backend exists. 952 bool HasSyncingBackend() const; 953 954 // Update first sync time stored in preferences 955 void UpdateFirstSyncTimePref(); 956 957 // Clear browsing data since first sync during rollback. 958 void ClearBrowsingDataSinceFirstSync(); 959 960 // Factory used to create various dependent objects. 961 scoped_ptr<ProfileSyncComponentsFactory> factory_; 962 963 // The profile whose data we are synchronizing. 964 Profile* profile_; 965 966 // The class that handles getting, setting, and persisting sync 967 // preferences. 968 sync_driver::SyncPrefs sync_prefs_; 969 970 // TODO(ncarter): Put this in a profile, once there is UI for it. 971 // This specifies where to find the sync server. 972 const GURL sync_service_url_; 973 974 // The last time we detected a successful transition from SYNCING state. 975 // Our backend notifies us whenever we should take a new snapshot. 976 base::Time last_synced_time_; 977 978 // The time that OnConfigureStart is called. This member is zero if 979 // OnConfigureStart has not yet been called, and is reset to zero once 980 // OnConfigureDone is called. 981 base::Time sync_configure_start_time_; 982 983 // Indicates if this is the first time sync is being configured. This value 984 // is equal to !HasSyncSetupCompleted() at the time of OnBackendInitialized(). 985 bool is_first_time_sync_configure_; 986 987 // List of available data type controllers for directory types. 988 browser_sync::DataTypeController::TypeMap directory_data_type_controllers_; 989 990 // Whether the SyncBackendHost has been initialized. 991 bool backend_initialized_; 992 993 // Set when sync receives DISABLED_BY_ADMIN error from server. Prevents 994 // ProfileSyncService from starting backend till browser restarted or user 995 // signed out. 996 bool sync_disabled_by_admin_; 997 998 // Set to true if a signin has completed but we're still waiting for the 999 // backend to refresh its credentials. 1000 bool is_auth_in_progress_; 1001 1002 // Encapsulates user signin - used to set/get the user's authenticated 1003 // email address. 1004 const scoped_ptr<ManagedUserSigninManagerWrapper> signin_; 1005 1006 // Information describing an unrecoverable error. 1007 UnrecoverableErrorReason unrecoverable_error_reason_; 1008 std::string unrecoverable_error_message_; 1009 tracked_objects::Location unrecoverable_error_location_; 1010 1011 // Manages the start and stop of the directory data types. 1012 scoped_ptr<browser_sync::DataTypeManager> directory_data_type_manager_; 1013 1014 // Manager for the non-blocking data types. 1015 browser_sync::NonBlockingDataTypeManager non_blocking_data_type_manager_; 1016 1017 ObserverList<ProfileSyncServiceBase::Observer> observers_; 1018 ObserverList<browser_sync::ProtocolEventObserver> protocol_event_observers_; 1019 ObserverList<syncer::TypeDebugInfoObserver> type_debug_info_observers_; 1020 1021 syncer::SyncJsController sync_js_controller_; 1022 1023 // This allows us to gracefully handle an ABORTED return code from the 1024 // DataTypeManager in the event that the server informed us to cease and 1025 // desist syncing immediately. 1026 bool expect_sync_configuration_aborted_; 1027 1028 // Sometimes we need to temporarily hold on to a passphrase because we don't 1029 // yet have a backend to send it to. This happens during initialization as 1030 // we don't StartUp until we have a valid token, which happens after valid 1031 // credentials were provided. 1032 std::string cached_passphrase_; 1033 1034 // The current set of encrypted types. Always a superset of 1035 // syncer::Cryptographer::SensitiveTypes(). 1036 syncer::ModelTypeSet encrypted_types_; 1037 1038 // Whether we want to encrypt everything. 1039 bool encrypt_everything_; 1040 1041 // Whether we're waiting for an attempt to encryption all sync data to 1042 // complete. We track this at this layer in order to allow the user to cancel 1043 // if they e.g. don't remember their explicit passphrase. 1044 bool encryption_pending_; 1045 1046 scoped_ptr<browser_sync::BackendMigrator> migrator_; 1047 1048 // This is the last |SyncProtocolError| we received from the server that had 1049 // an action set on it. 1050 syncer::SyncProtocolError last_actionable_error_; 1051 1052 // Exposes sync errors to the UI. 1053 scoped_ptr<SyncErrorController> sync_error_controller_; 1054 1055 // Tracks the set of failed data types (those that encounter an error 1056 // or must delay loading for some reason). 1057 browser_sync::FailedDataTypesHandler failed_data_types_handler_; 1058 1059 browser_sync::DataTypeManager::ConfigureStatus configure_status_; 1060 1061 // The set of currently enabled sync experiments. 1062 syncer::Experiments current_experiments_; 1063 1064 // Sync's internal debug info listener. Used to record datatype configuration 1065 // and association information. 1066 syncer::WeakHandle<syncer::DataTypeDebugInfoListener> debug_info_listener_; 1067 1068 // A thread where all the sync operations happen. 1069 // OWNERSHIP Notes: 1070 // * Created when backend starts for the first time. 1071 // * If sync is disabled, PSS claims ownership from backend. 1072 // * If sync is reenabled, PSS passes ownership to new backend. 1073 scoped_ptr<base::Thread> sync_thread_; 1074 1075 // ProfileSyncService uses this service to get access tokens. 1076 ProfileOAuth2TokenService* const oauth2_token_service_; 1077 1078 // ProfileSyncService needs to remember access token in order to invalidate it 1079 // with OAuth2TokenService. 1080 std::string access_token_; 1081 1082 // ProfileSyncService needs to hold reference to access_token_request_ for 1083 // the duration of request in order to receive callbacks. 1084 scoped_ptr<OAuth2TokenService::Request> access_token_request_; 1085 1086 // If RequestAccessToken fails with transient error then retry requesting 1087 // access token with exponential backoff. 1088 base::OneShotTimer<ProfileSyncService> request_access_token_retry_timer_; 1089 net::BackoffEntry request_access_token_backoff_; 1090 1091 base::WeakPtrFactory<ProfileSyncService> weak_factory_; 1092 1093 // We don't use |weak_factory_| for the StartupController because the weak 1094 // ptrs should be bound to the lifetime of ProfileSyncService and not to the 1095 // [Initialize -> sync disabled/shutdown] lifetime. We don't pass 1096 // StartupController an Unretained reference to future-proof against 1097 // the controller impl changing to post tasks. Therefore, we have a separate 1098 // factory. 1099 base::WeakPtrFactory<ProfileSyncService> startup_controller_weak_factory_; 1100 1101 // States related to sync token and connection. 1102 base::Time connection_status_update_time_; 1103 syncer::ConnectionStatus connection_status_; 1104 base::Time token_request_time_; 1105 base::Time token_receive_time_; 1106 GoogleServiceAuthError last_get_token_error_; 1107 base::Time next_token_request_time_; 1108 1109 // Locally owned SyncableService implementations. 1110 scoped_ptr<SessionsSyncManager> sessions_sync_manager_; 1111 1112 scoped_ptr<syncer::NetworkResources> network_resources_; 1113 1114 browser_sync::StartupController startup_controller_; 1115 1116 browser_sync::BackupRollbackController backup_rollback_controller_; 1117 1118 // Mode of current backend. 1119 BackendMode backend_mode_; 1120 1121 // When browser starts, delay sync backup/rollback backend start for this 1122 // time. 1123 base::TimeDelta backup_start_delay_; 1124 1125 base::Callback<void(Profile*, base::Time, base::Time)> clear_browsing_data_; 1126 1127 DISALLOW_COPY_AND_ASSIGN(ProfileSyncService); 1128 }; 1129 1130 bool ShouldShowActionOnUI( 1131 const syncer::SyncProtocolError& error); 1132 1133 1134 #endif // CHROME_BROWSER_SYNC_PROFILE_SYNC_SERVICE_H_ 1135